├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── SoftwareModem.sln ├── SoftwareModem ├── App.config ├── App.xaml ├── App.xaml.cs ├── Detectors.cs ├── MainWindow.xaml ├── MainWindow.xaml.cs ├── Modem.cs ├── Properties │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ ├── Settings.Designer.cs │ └── Settings.settings ├── SoftwareModem.csproj ├── ToneGenerator.cs └── packages.config └── diagram-modem.png /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | 9 | # Build results 10 | [Dd]ebug/ 11 | [Dd]ebugPublic/ 12 | [Rr]elease/ 13 | x64/ 14 | build/ 15 | bld/ 16 | [Bb]in/ 17 | [Oo]bj/ 18 | 19 | # Roslyn cache directories 20 | *.ide/ 21 | 22 | # MSTest test Results 23 | [Tt]est[Rr]esult*/ 24 | [Bb]uild[Ll]og.* 25 | 26 | #NUNIT 27 | *.VisualState.xml 28 | TestResult.xml 29 | 30 | # Build Results of an ATL Project 31 | [Dd]ebugPS/ 32 | [Rr]eleasePS/ 33 | dlldata.c 34 | 35 | *_i.c 36 | *_p.c 37 | *_i.h 38 | *.ilk 39 | *.meta 40 | *.obj 41 | *.pch 42 | *.pdb 43 | *.pgc 44 | *.pgd 45 | *.rsp 46 | *.sbr 47 | *.tlb 48 | *.tli 49 | *.tlh 50 | *.tmp 51 | *.tmp_proj 52 | *.log 53 | *.vspscc 54 | *.vssscc 55 | .builds 56 | *.pidb 57 | *.svclog 58 | *.scc 59 | 60 | # Chutzpah Test files 61 | _Chutzpah* 62 | 63 | # Visual C++ cache files 64 | ipch/ 65 | *.aps 66 | *.ncb 67 | *.opensdf 68 | *.sdf 69 | *.cachefile 70 | 71 | # Visual Studio profiler 72 | *.psess 73 | *.vsp 74 | *.vspx 75 | 76 | # TFS 2012 Local Workspace 77 | $tf/ 78 | 79 | # Guidance Automation Toolkit 80 | *.gpState 81 | 82 | # ReSharper is a .NET coding add-in 83 | _ReSharper*/ 84 | *.[Rr]e[Ss]harper 85 | *.DotSettings.user 86 | 87 | # JustCode is a .NET coding addin-in 88 | .JustCode 89 | 90 | # TeamCity is a build add-in 91 | _TeamCity* 92 | 93 | # DotCover is a Code Coverage Tool 94 | *.dotCover 95 | 96 | # NCrunch 97 | _NCrunch_* 98 | .*crunch*.local.xml 99 | 100 | # MightyMoose 101 | *.mm.* 102 | AutoTest.Net/ 103 | 104 | # Web workbench (sass) 105 | .sass-cache/ 106 | 107 | # Installshield output folder 108 | [Ee]xpress/ 109 | 110 | # DocProject is a documentation generator add-in 111 | DocProject/buildhelp/ 112 | DocProject/Help/*.HxT 113 | DocProject/Help/*.HxC 114 | DocProject/Help/*.hhc 115 | DocProject/Help/*.hhk 116 | DocProject/Help/*.hhp 117 | DocProject/Help/Html2 118 | DocProject/Help/html 119 | 120 | # Click-Once directory 121 | publish/ 122 | 123 | # Publish Web Output 124 | *.[Pp]ublish.xml 125 | *.azurePubxml 126 | ## TODO: Comment the next line if you want to checkin your 127 | ## web deploy settings but do note that will include unencrypted 128 | ## passwords 129 | #*.pubxml 130 | 131 | # NuGet Packages Directory 132 | packages/* 133 | ## TODO: If the tool you use requires repositories.config 134 | ## uncomment the next line 135 | #!packages/repositories.config 136 | 137 | # Enable "build/" folder in the NuGet Packages folder since 138 | # NuGet packages use it for MSBuild targets. 139 | # This line needs to be after the ignore of the build folder 140 | # (and the packages folder if the line above has been uncommented) 141 | !packages/build/ 142 | 143 | # Windows Azure Build Output 144 | csx/ 145 | *.build.csdef 146 | 147 | # Windows Store app package directory 148 | AppPackages/ 149 | 150 | # Others 151 | sql/ 152 | *.Cache 153 | ClientBin/ 154 | [Ss]tyle[Cc]op.* 155 | ~$* 156 | *~ 157 | *.dbmdl 158 | *.dbproj.schemaview 159 | *.pfx 160 | *.publishsettings 161 | node_modules/ 162 | 163 | # RIA/Silverlight projects 164 | Generated_Code/ 165 | 166 | # Backup & report files from converting an old project file 167 | # to a newer Visual Studio version. Backup files are not needed, 168 | # because we have git ;-) 169 | _UpgradeReport_Files/ 170 | Backup*/ 171 | UpgradeLog*.XML 172 | UpgradeLog*.htm 173 | 174 | # SQL Server files 175 | *.mdf 176 | *.ldf 177 | 178 | # Business Intelligence projects 179 | *.rdl.data 180 | *.bim.layout 181 | *.bim_*.settings 182 | 183 | # Microsoft Fakes 184 | FakesAssemblies/ 185 | 186 | # LightSwitch generated files 187 | GeneratedArtifacts/ 188 | _Pvt_Extensions/ 189 | ModelManifest.xml -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Software Modem 2 | 3 | An implementation of the ITU-T V.21 modem standard, working on a PC over a sound card. 4 | 5 | This program uses your computer's sound card to communicate using the V.21 standard, which allows for communications at up to 300 bps. It can actually talk to a modem, both in call and answer mode, using a small electronic circuit that connects them. 6 | 7 | You can see a demo of this program in action, including those beautiful modem noises, at https://youtu.be/yfGg2qu2P6s. 8 | 9 | This program was written in C# on Visual Studio Community 2013, with the NAudio library. 10 | 11 | Note: this is _not_ good code. I wrote it to learn C#, and I wasn't entirely successful at it. Feel free to lift and reuse the code under the terms of its license, but don't expect it to work right as-is, especially since it's very old. 12 | 13 | ## Hardware 14 | 15 | If you'd like to connect two computers using this program, you only need a couple of audio cables: connect the line input from one computer to the line output of the other computer and vice versa. Theoretically you could also connect two copies of the program running on the same computer by connecting the computer's line out with its line in using a single audio cable. I haven't tried it, so YMMV. 16 | 17 | You can also connect the computer's sound card to an actual modem using a small electronic circuit that simulates a phone line. You are going to need: 18 | 19 | 1. A 9-volt battery. 20 | 2. A 9-volt battery connector. 21 | 2. A 470-Ohm resistor. 22 | 3. A 150-Ohm resistor. 23 | 4. A 600/600 Ohm transformer. One of the windings must have a center tap. You can scavenge one from an old modem or telephone, or buy one (I used the Xicon 42TL016-RC, but there are many in the market). 24 | 5. A length of phone cable with an RJ11 modular connector. 25 | 6. Two 3.5 mm audio jacks. 26 | 7. A modem. 27 | 8. (Recommended) A corded phone 28 | 29 | You can use a higher voltage battery if you want, but make sure to scale the 470-Ohm resistor up as well so that the current is limited to some 20-25 mA. 30 | 31 | **WARNING**: This circuit is designed to simulate a phone line so you can connect a modem or telephone directly to your computer. It is not designed to connect the computer to a phone line. This circuit uses 9 volt DC, while phone lines may present up to 100 volts AC, which will then go into your sound card. This means that **you will burn your computer if you connect it to the phone line using this circuit**. 32 | 33 | ![Line simulator diagram](diagram-modem.png) 34 | 35 | Start by connecting the components as in the diagram. You may use a breadboard, a PCB, or even solder them "dead bug style". On the modem side, connect the battery and the resistor to the transformer's outer taps, and connect the phone cable to the battery and resistor. On the other side, connect the resistor to the center tap and connect the other end of the resistor to both jacks' sleeves. Then connect an outer tap to one of the jack's tip, and do the same for the other outer tap and jack. 36 | 37 | Then connect one of the jacks to your sound card's "line in" socket, and the other jack to the "line out" or "headphone" socket. Both jacks are connected in the same way, so it's indifferent which one is connected where. 38 | 39 | To test the circuit you can plug a corded telephone to the RJ11 connector, and try playing and recording sounds over the headset. 40 | 41 | To use the circuit, just replace the telephone with a modem (or, if you have two RJ11 connectors in parallel, leave the telephone connected and plug the other connector into the modem). 42 | 43 | ## How to use 44 | 45 | After you start the program, select the correct line in device in the drop down box. 46 | 47 | If you are using a modem on the remote side, configure the terminal emulator with 8 data bits, no parity, and 1 stop bit (8N1). 48 | 49 | ### Make a call 50 | 51 | On the Software Modem window, press the "Call" button. On the remote side, press the "Answer" button or type "ATA" if you are using a modem with a terminal emulator. Wait a few seconds until the terminal emulator displays "CONNECT". 52 | 53 | ### Receive a call 54 | 55 | On the remote side, press the "Call" button or type "ATD" if you are using a modem with a terminal emulator, and then press "Answer" on the Software Modem window. Wait a few seconds until the terminal emulator displays "CONNECT". 56 | 57 | ### Terminate a call 58 | 59 | Press the "Hang up" button on the Software Modem window. On the remote side, press the "Hang up" button or, if you are using a modem with a terminal emulator, type "+++" without pressing Return, wait for "OK" to be displayed, and then type "ATH". 60 | 61 | -------------------------------------------------------------------------------- /SoftwareModem.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.31101.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SoftwareModem", "SoftwareModem\SoftwareModem.csproj", "{BB0C9DEF-53F4-4868-937C-251D20B585B7}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {BB0C9DEF-53F4-4868-937C-251D20B585B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {BB0C9DEF-53F4-4868-937C-251D20B585B7}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {BB0C9DEF-53F4-4868-937C-251D20B585B7}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {BB0C9DEF-53F4-4868-937C-251D20B585B7}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /SoftwareModem/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /SoftwareModem/App.xaml: -------------------------------------------------------------------------------- 1 |  5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /SoftwareModem/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Configuration; 4 | using System.Data; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using System.Windows; 8 | 9 | namespace SoftwareModem 10 | { 11 | /// 12 | /// Interaction logic for App.xaml 13 | /// 14 | public partial class App : Application 15 | { 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /SoftwareModem/Detectors.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Jacobo Tarrío Barreiro. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Numerics; 17 | 18 | namespace SoftwareModem 19 | { 20 | abstract class BaseDetector 21 | { 22 | protected int sampleRate; 23 | protected int frequency; 24 | protected int maxDev; 25 | private bool ignoreInversions; 26 | private ComplexFilter lagFilter; 27 | private DoubleFilter freqFilter; 28 | private DoubleFilter lockFilter; 29 | private double phase; 30 | 31 | public BaseDetector(int sampleRate, int frequency, int maxDev, bool ignoreInversions) 32 | { 33 | this.sampleRate = sampleRate; 34 | this.frequency = frequency; 35 | this.maxDev = Math.Abs(maxDev); 36 | this.ignoreInversions = ignoreInversions; 37 | if (ignoreInversions) 38 | { 39 | this.frequency *= 2; 40 | this.maxDev *= 2; 41 | } 42 | this.lagFilter = new ComplexFilter(sampleRate, maxDev); 43 | this.freqFilter = new DoubleFilter(sampleRate, maxDev); 44 | this.lockFilter = new DoubleFilter(sampleRate, 15); 45 | this.phase = 0; 46 | } 47 | 48 | protected abstract bool ProcessSample(double pllFreq, double pllLock, byte[] bytes, int byteCount, int i); 49 | 50 | public void ReceiveSamples(byte[] bytes, int byteCount) 51 | { 52 | for (int i = 0; i < byteCount; i += 4) 53 | { 54 | int sample16 = (short)(bytes[i] + 256 * bytes[i + 1]); 55 | double sample = (double)sample16 / 32768; 56 | if (ignoreInversions) 57 | { 58 | sample *= sample; 59 | } 60 | var pllRef = Complex.FromPolarCoordinates(1, -phase); 61 | var pllLag = lagFilter.Add(sample * pllRef); 62 | var angle = pllLag.Phase; 63 | var correction = Math.Max(-maxDev, Math.Min(maxDev, (angle / 65) * sampleRate / (2 * Math.PI))); 64 | var pllFreq = freqFilter.Add(correction); 65 | var pllLock = lockFilter.Add(pllLag == 0 ? 1 : sample / pllLag.Magnitude); 66 | phase += 2 * Math.PI * (frequency + pllFreq) / sampleRate; 67 | if (phase > Math.PI) 68 | { 69 | phase -= 2 * Math.PI; 70 | } 71 | if (ProcessSample(pllFreq, pllLock, bytes, byteCount, i)) 72 | { 73 | return; 74 | } 75 | } 76 | } 77 | } 78 | 79 | class ANSamDetector : BaseDetector 80 | { 81 | private const double DetectThreshold = 10; 82 | 83 | private int samplesOverThreshold = -1; 84 | 85 | public ANSamDetector(int sampleRate) : base(sampleRate, 2100, 30, true) { } 86 | 87 | protected override bool ProcessSample(double pllFreq, double pllLock, byte[] bytes, int byteCount, int i) 88 | { 89 | if (pllLock < DetectThreshold) 90 | { 91 | ++samplesOverThreshold; 92 | if (samplesOverThreshold > sampleRate / 2) 93 | { 94 | byte[] buffer = new byte[byteCount - i]; 95 | Array.Copy(bytes, i, buffer, 0, byteCount - i); 96 | DetectANSam(this, new DetectANSAmHandlerEventArgs(buffer)); 97 | return true; 98 | } 99 | } 100 | else 101 | { 102 | samplesOverThreshold = 0; 103 | } 104 | return false; 105 | } 106 | 107 | public delegate void DetectANSamHandler(object sender, DetectANSAmHandlerEventArgs e); 108 | public event DetectANSamHandler DetectANSam; 109 | 110 | public class DetectANSAmHandlerEventArgs : EventArgs 111 | { 112 | public byte[] Buffer { get; private set; } 113 | public DetectANSAmHandlerEventArgs(byte[] buffer) 114 | { 115 | Buffer = buffer; 116 | } 117 | } 118 | } 119 | 120 | class BiFSKDetector : BaseDetector 121 | { 122 | private const double DetectThreshold = 10; 123 | 124 | private int samplesPerBitNominal; 125 | private double samplesPerBitActual; 126 | private int samplesSinceTransition; 127 | private int samplesSinceLastBit; 128 | private bool lastBitSeen; 129 | 130 | public BiFSKDetector(int sampleRate, int freq) 131 | : base(sampleRate, freq, 200, false) 132 | { 133 | this.samplesPerBitNominal = sampleRate / 300; 134 | this.samplesPerBitActual = samplesPerBitNominal; 135 | this.samplesSinceTransition = -1; 136 | this.samplesSinceLastBit = -1; 137 | this.lastBitSeen = true; 138 | } 139 | 140 | protected override bool ProcessSample(double pllFreq, double pllLock, byte[] bytes, int byteCount, int i) 141 | { 142 | var isBitOne = pllFreq < 0; 143 | if (samplesSinceLastBit >= samplesPerBitActual) 144 | { 145 | OnDetectTone(isBitOne); 146 | samplesSinceLastBit = 0; 147 | } 148 | else if (samplesSinceLastBit >= 0) 149 | { 150 | ++samplesSinceLastBit; 151 | } 152 | 153 | if (isBitOne != lastBitSeen) 154 | { 155 | lastBitSeen = isBitOne; 156 | var numBits = Math.Round((double)samplesSinceTransition / samplesPerBitActual); 157 | var samplesPerBit = samplesSinceTransition / numBits; 158 | if (samplesSinceTransition < 0 || numBits > 10 || samplesPerBit > samplesPerBitNominal * 1.12) 159 | { 160 | samplesSinceTransition = 0; 161 | samplesSinceLastBit = (int)(samplesPerBitActual / 2); 162 | } 163 | else if (samplesPerBit > samplesPerBitNominal * 0.88) 164 | { 165 | samplesPerBitActual = (3 * samplesPerBitActual + samplesPerBit) / 4; 166 | samplesSinceTransition = 0; 167 | samplesSinceLastBit = (int)(samplesPerBitActual / 2); 168 | } 169 | } 170 | else if (samplesSinceTransition >= 0) 171 | { 172 | ++samplesSinceTransition; 173 | } 174 | return false; 175 | } 176 | 177 | public delegate void DetectToneHandler(object sender, DetectToneEventArgs e); 178 | public event DetectToneHandler DetectTone; 179 | 180 | private void OnDetectTone(bool toneForOne) 181 | { 182 | DetectTone(this, new DetectToneEventArgs(toneForOne)); 183 | } 184 | 185 | public class DetectToneEventArgs : EventArgs 186 | { 187 | public bool ToneForOne { get; private set; } 188 | public DetectToneEventArgs(bool toneForOne) 189 | { 190 | ToneForOne = toneForOne; 191 | } 192 | } 193 | } 194 | 195 | class DoubleFilter 196 | { 197 | private double alpha; 198 | private double y; 199 | public DoubleFilter(int sampleRate, double rc) 200 | { 201 | this.alpha = 2 * Math.PI * rc / (sampleRate + 2 * Math.PI * rc); 202 | this.y = 0; 203 | } 204 | public double Add(double x) 205 | { 206 | y += alpha * (x - y); 207 | return y; 208 | } 209 | } 210 | 211 | class ComplexFilter 212 | { 213 | private double alpha; 214 | private Complex y; 215 | public ComplexFilter(int sampleRate, double rc) 216 | { 217 | this.alpha = 2 * Math.PI * rc / (sampleRate + 2 * Math.PI * rc); 218 | this.y = Complex.Zero; 219 | } 220 | public Complex Add(Complex x) 221 | { 222 | y += alpha * (x - y); 223 | return y; 224 | } 225 | } 226 | 227 | } 228 | -------------------------------------------------------------------------------- /SoftwareModem/MainWindow.xaml: -------------------------------------------------------------------------------- 1 |  5 | 6 |