├── .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 | 
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 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/SoftwareModem/MainWindow.xaml.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 NAudio.CoreAudioApi;
16 | using NAudio.Wave;
17 | using System;
18 | using System.Windows;
19 |
20 | namespace SoftwareModem
21 | {
22 | ///
23 | /// Interaction logic for MainWindow.xaml
24 | ///
25 | public partial class MainWindow : Window
26 | {
27 | private Modem modem;
28 | private WasapiCapture capture;
29 | private WaveOutEvent waveOut;
30 |
31 | public MainWindow()
32 | {
33 | InitializeComponent();
34 | ScanDevices();
35 | }
36 |
37 | private void CallButton_Click(object sender, RoutedEventArgs e)
38 | {
39 | modem = new Modem();
40 | capture = GetCaptureDevice();
41 | waveOut = new WaveOutEvent();
42 | var playProvider = modem.Call(capture);
43 | modem.ByteReceived += modem_ByteReceived;
44 | waveOut.Init(playProvider);
45 | waveOut.Play();
46 | capture.StartRecording();
47 | HangupButton.IsEnabled = true;
48 | CallButton.IsEnabled = false;
49 | AnswerButton.IsEnabled = false;
50 | }
51 |
52 | private void AnswerButton_Click(object sender, RoutedEventArgs e)
53 | {
54 | modem = new Modem();
55 | capture = GetCaptureDevice();
56 | waveOut = new WaveOutEvent();
57 | var playProvider = modem.Answer(capture);
58 | modem.ByteReceived += modem_ByteReceived;
59 | waveOut.Init(playProvider);
60 | waveOut.Play();
61 | capture.StartRecording();
62 | HangupButton.IsEnabled = true;
63 | CallButton.IsEnabled = false;
64 | AnswerButton.IsEnabled = false;
65 | }
66 |
67 | private void HangupButton_Click(object sender, RoutedEventArgs e)
68 | {
69 | modem.Hangup();
70 | capture.StopRecording();
71 | waveOut.Stop();
72 | capture.Dispose();
73 | waveOut.Dispose();
74 | capture = null;
75 | waveOut = null;
76 | HangupButton.IsEnabled = false;
77 | CallButton.IsEnabled = true;
78 | AnswerButton.IsEnabled = true;
79 | }
80 |
81 | private void modem_ByteReceived(object sender, ByteReceivedEventArgs e)
82 | {
83 | Dispatcher.BeginInvoke(new Action(() => AddCharacter(e.Byte)));
84 | }
85 |
86 | private void AddCharacter(byte b)
87 | {
88 | OutputBox.Text += Char.ConvertFromUtf32(b);
89 | }
90 |
91 | private void ScanDevices()
92 | {
93 | var enumerator = new MMDeviceEnumerator();
94 | lineInBox.ItemsSource = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active);
95 | var selectedInput = enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Multimedia);
96 | for (var i = 0; i < lineInBox.Items.Count; ++i)
97 | {
98 | if ((lineInBox.Items[i] as MMDevice).ID == selectedInput.ID)
99 | {
100 | lineInBox.SelectedIndex = i;
101 | }
102 | }
103 | }
104 |
105 | private WasapiCapture GetCaptureDevice()
106 | {
107 | var device = lineInBox.SelectedItem as MMDevice;
108 | var capture = new NAudio.CoreAudioApi.WasapiCapture(device);
109 | capture.ShareMode = AudioClientShareMode.Shared;
110 | capture.WaveFormat = new WaveFormat();
111 | return capture;
112 | }
113 |
114 | private void SendButton_Click(object sender, RoutedEventArgs e)
115 | {
116 | var bytes = new byte[InputBox.Text.Length];
117 | for (int i = 0; i < InputBox.Text.Length; ++i)
118 | {
119 | var chr = Char.ConvertToUtf32(InputBox.Text, i);
120 | if (chr < 256)
121 | {
122 | bytes[i] = (byte)chr;
123 | }
124 | else
125 | {
126 | bytes[i] = (byte)'?';
127 | }
128 | }
129 | modem.SendData(bytes);
130 | }
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/SoftwareModem/Modem.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 NAudio.Wave;
16 | using System;
17 | using System.Collections.Generic;
18 | using System.Linq;
19 |
20 | namespace SoftwareModem
21 | {
22 | class Modem
23 | {
24 | private const int Channel1Freq = 1080;
25 | private const int Channel2Freq = 1750;
26 |
27 | private readonly int[] CallMenu = new int[] {
28 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
29 | 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
30 | 0, 1, 0, 0, 0, 0, 0, 1, 1, 1,
31 | 0, 1, 0, 1, 0, 0, 0, 0, 0, 1,
32 | 0, 0, 0, 0, 0, 1, 0, 0, 0, 1,
33 | 0, 0, 0, 0, 0, 1, 0, 0, 1, 1
34 | };
35 |
36 | private CallState state;
37 | private ANSamDetector ansamDetector;
38 | private BiFSKDetector toneDetector;
39 | private ToneGenerator toneGenerator;
40 | private List receivedMenu;
41 | private List recvData;
42 | private int currentDatum = 0;
43 | private int currentBit = 0;
44 |
45 | public void Reset()
46 | {
47 | ansamDetector = null;
48 | toneDetector = null;
49 | toneGenerator = null;
50 | receivedMenu = null;
51 | currentDatum = 0;
52 | currentBit = 0;
53 | recvData = new List();
54 | }
55 |
56 | public IWaveProvider Call(IWaveIn waveIn)
57 | {
58 | Reset();
59 | var sampleRate = waveIn.WaveFormat.SampleRate;
60 | state = CallState.WaitForAnswer;
61 | toneDetector = new BiFSKDetector(sampleRate, Channel2Freq);
62 | toneDetector.DetectTone += ToneDetected;
63 | toneGenerator = new ToneGenerator(sampleRate, Channel1Freq);
64 | ansamDetector = new ANSamDetector(sampleRate);
65 | ansamDetector.DetectANSam += ANSamDetected;
66 | waveIn.DataAvailable += WaveInDataAvailable;
67 | return toneGenerator;
68 | }
69 |
70 | public IWaveProvider Answer(IWaveIn waveIn)
71 | {
72 | Reset();
73 | var sampleRate = waveIn.WaveFormat.SampleRate;
74 | state = CallState.WaitForCallMenu;
75 | toneDetector = new BiFSKDetector(sampleRate, Channel1Freq);
76 | toneDetector.DetectTone += ToneDetected;
77 | toneGenerator = new ToneGenerator(sampleRate, Channel2Freq);
78 | toneGenerator.SendANSam();
79 | waveIn.DataAvailable += WaveInDataAvailable;
80 | return toneGenerator;
81 | }
82 |
83 | public void Hangup()
84 | {
85 | state = CallState.Hangup;
86 | Reset();
87 | }
88 |
89 | public void SendData(byte[] data)
90 | {
91 | int[] bits = new int[data.Length * 10];
92 | for (int i = 0; i < data.Length; ++i) {
93 | bits[i * 10] = 0;
94 | bits[i * 10 + 9] = 1;
95 | for (int j = 0; j < 8; ++j) {
96 | bits[i * 10 + j + 1] = (data[i] >> j) & 0x01;
97 | }
98 | }
99 | toneGenerator.EnqueueBits(bits);
100 | }
101 |
102 | public delegate void ByteReceivedHandler(object sender, ByteReceivedEventArgs e);
103 | public event ByteReceivedHandler ByteReceived;
104 |
105 | private void WaveInDataAvailable(object sender, WaveInEventArgs e)
106 | {
107 | if (ansamDetector != null)
108 | {
109 | ansamDetector.ReceiveSamples(e.Buffer, e.BytesRecorded);
110 | }
111 | else if (toneDetector != null)
112 | {
113 | toneDetector.ReceiveSamples(e.Buffer, e.BytesRecorded);
114 | }
115 | }
116 |
117 | private void ANSamDetected(object sender, ANSamDetector.DetectANSAmHandlerEventArgs e)
118 | {
119 | ansamDetector = null;
120 | state = CallState.SendCallMenu;
121 | toneGenerator.Repeat(true, CallMenu);
122 | toneDetector.ReceiveSamples(e.Buffer, e.Buffer.Length);
123 | }
124 |
125 | private void ToneDetected(object sender, BiFSKDetector.DetectToneEventArgs e)
126 | {
127 | currentDatum = ((e.ToneForOne ? 1 : 0) << 9) | (currentDatum >> 1);
128 | currentBit = currentBit + 1;
129 | if (currentDatum == 0x3ff)
130 | {
131 | recvData.Clear();
132 | currentBit = 0;
133 | }
134 | else if ((currentDatum & 0x201) == 0x200 && currentBit >= 10)
135 | {
136 | currentBit = 0;
137 | int recvByte = (currentDatum >> 1) & 0xff;
138 | recvData.Add((byte)recvByte);
139 | ByteDetected();
140 | }
141 | }
142 |
143 | private void ByteDetected()
144 | {
145 | switch (state)
146 | {
147 | case CallState.SendCallMenu:
148 | if (recvData.Count == 5 && recvData[0] == 0xe0 && recvData[1] == 0xc1 && (recvData[4] & 0x80) == 0x80)
149 | {
150 | if (receivedMenu != null && recvData.SequenceEqual(receivedMenu)) {
151 | toneGenerator.PrepareForData(true);
152 | recvData.Clear();
153 | state = CallState.Data;
154 | }
155 | else
156 | {
157 | receivedMenu = new List(recvData);
158 | recvData.Clear();
159 | }
160 | }
161 | break;
162 | case CallState.WaitForCallMenu:
163 | if (recvData.Count == 5 && recvData[0] == 0xe0 && recvData[1] == 0xc1 && (recvData[4] & 0x80) == 0x80)
164 | {
165 | if (receivedMenu != null && recvData.SequenceEqual(receivedMenu))
166 | {
167 | recvData.Clear();
168 | state = CallState.SendJointMenu;
169 | toneGenerator.Repeat(false, CallMenu);
170 | }
171 | else
172 | {
173 | receivedMenu = new List(recvData);
174 | recvData.Clear();
175 | }
176 | }
177 | break;
178 | case CallState.SendJointMenu:
179 | if (recvData.Count >= 3 && recvData[recvData.Count - 3] == 0 && recvData[recvData.Count - 2] == 0 && recvData[recvData.Count - 1] == 0)
180 | {
181 | toneGenerator.PrepareForData(false);
182 | recvData.Clear();
183 | state = CallState.Data;
184 | }
185 | break;
186 | case CallState.Data:
187 | foreach (var b in recvData)
188 | {
189 | ByteReceived(this, new ByteReceivedEventArgs(b));
190 | }
191 | recvData.Clear();
192 | break;
193 | }
194 | }
195 |
196 | private enum CallState
197 | {
198 | WaitForAnswer, SendCallMenu, WaitForCallMenu, ReceiveCallMenu, SendJointMenu, WaitForData, Data, Hangup
199 | }
200 |
201 | private class RecvData
202 | {
203 | private List bytes = new List();
204 | public void AddByte(int b)
205 | {
206 | bytes.Add((byte)b);
207 | }
208 |
209 | public List Data { get { return bytes; } }
210 | }
211 | }
212 |
213 | public class ByteReceivedEventArgs : EventArgs
214 | {
215 | public byte Byte { get; private set; }
216 |
217 | public ByteReceivedEventArgs(byte b)
218 | {
219 | this.Byte = b;
220 | }
221 | }
222 |
223 | }
224 |
--------------------------------------------------------------------------------
/SoftwareModem/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Resources;
3 | using System.Runtime.CompilerServices;
4 | using System.Runtime.InteropServices;
5 | using System.Windows;
6 |
7 | // General Information about an assembly is controlled through the following
8 | // set of attributes. Change these attribute values to modify the information
9 | // associated with an assembly.
10 | [assembly: AssemblyTitle("SoftwareModem")]
11 | [assembly: AssemblyDescription("")]
12 | [assembly: AssemblyConfiguration("")]
13 | [assembly: AssemblyCompany("")]
14 | [assembly: AssemblyProduct("SoftwareModem")]
15 | [assembly: AssemblyCopyright("Copyright © 2014")]
16 | [assembly: AssemblyTrademark("")]
17 | [assembly: AssemblyCulture("")]
18 |
19 | // Setting ComVisible to false makes the types in this assembly not visible
20 | // to COM components. If you need to access a type in this assembly from
21 | // COM, set the ComVisible attribute to true on that type.
22 | [assembly: ComVisible(false)]
23 |
24 | //In order to begin building localizable applications, set
25 | //CultureYouAreCodingWith in your .csproj file
26 | //inside a . For example, if you are using US english
27 | //in your source files, set the to en-US. Then uncomment
28 | //the NeutralResourceLanguage attribute below. Update the "en-US" in
29 | //the line below to match the UICulture setting in the project file.
30 |
31 | //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
32 |
33 |
34 | [assembly: ThemeInfo(
35 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
36 | //(used if a resource is not found in the page,
37 | // or application resource dictionaries)
38 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
39 | //(used if a resource is not found in the page,
40 | // app, or any theme specific resource dictionaries)
41 | )]
42 |
43 |
44 | // Version information for an assembly consists of the following four values:
45 | //
46 | // Major Version
47 | // Minor Version
48 | // Build Number
49 | // Revision
50 | //
51 | // You can specify all the values or you can default the Build and Revision Numbers
52 | // by using the '*' as shown below:
53 | // [assembly: AssemblyVersion("1.0.*")]
54 | [assembly: AssemblyVersion("1.0.0.0")]
55 | [assembly: AssemblyFileVersion("1.0.0.0")]
56 |
--------------------------------------------------------------------------------
/SoftwareModem/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.18444
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace SoftwareModem.Properties
12 | {
13 |
14 |
15 | ///
16 | /// A strongly-typed resource class, for looking up localized strings, etc.
17 | ///
18 | // This class was auto-generated by the StronglyTypedResourceBuilder
19 | // class via a tool like ResGen or Visual Studio.
20 | // To add or remove a member, edit your .ResX file then rerun ResGen
21 | // with the /str option, or rebuild your VS project.
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources
26 | {
27 |
28 | private static global::System.Resources.ResourceManager resourceMan;
29 |
30 | private static global::System.Globalization.CultureInfo resourceCulture;
31 |
32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
33 | internal Resources()
34 | {
35 | }
36 |
37 | ///
38 | /// Returns the cached ResourceManager instance used by this class.
39 | ///
40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
41 | internal static global::System.Resources.ResourceManager ResourceManager
42 | {
43 | get
44 | {
45 | if ((resourceMan == null))
46 | {
47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SoftwareModem.Properties.Resources", typeof(Resources).Assembly);
48 | resourceMan = temp;
49 | }
50 | return resourceMan;
51 | }
52 | }
53 |
54 | ///
55 | /// Overrides the current thread's CurrentUICulture property for all
56 | /// resource lookups using this strongly typed resource class.
57 | ///
58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
59 | internal static global::System.Globalization.CultureInfo Culture
60 | {
61 | get
62 | {
63 | return resourceCulture;
64 | }
65 | set
66 | {
67 | resourceCulture = value;
68 | }
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/SoftwareModem/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/SoftwareModem/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.18444
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace SoftwareModem.Properties
12 | {
13 |
14 |
15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
18 | {
19 |
20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
21 |
22 | public static Settings Default
23 | {
24 | get
25 | {
26 | return defaultInstance;
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/SoftwareModem/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/SoftwareModem/SoftwareModem.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {BB0C9DEF-53F4-4868-937C-251D20B585B7}
8 | WinExe
9 | Properties
10 | SoftwareModem
11 | SoftwareModem
12 | v4.5
13 | 512
14 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
15 | 4
16 |
17 |
18 | AnyCPU
19 | true
20 | full
21 | false
22 | bin\Debug\
23 | DEBUG;TRACE
24 | prompt
25 | 4
26 |
27 |
28 | AnyCPU
29 | pdbonly
30 | true
31 | bin\Release\
32 | TRACE
33 | prompt
34 | 4
35 |
36 |
37 |
38 | ..\packages\NAudio.1.7.2\lib\net35\NAudio.dll
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 | 4.0
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 | MSBuild:Compile
58 | Designer
59 |
60 |
61 | Code
62 |
63 |
64 |
65 | MSBuild:Compile
66 | Designer
67 |
68 |
69 | App.xaml
70 | Code
71 |
72 |
73 | MainWindow.xaml
74 | Code
75 |
76 |
77 |
78 |
79 |
80 | Code
81 |
82 |
83 | True
84 | True
85 | Resources.resx
86 |
87 |
88 | True
89 | Settings.settings
90 | True
91 |
92 |
93 | ResXFileCodeGenerator
94 | Resources.Designer.cs
95 |
96 |
97 |
98 | SettingsSingleFileGenerator
99 | Settings.Designer.cs
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
114 |
--------------------------------------------------------------------------------
/SoftwareModem/ToneGenerator.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.Collections.Concurrent;
17 |
18 | namespace SoftwareModem
19 | {
20 | class ToneGenerator : NAudio.Wave.WaveProvider32
21 | {
22 | private int sampleRate;
23 | private int freqOne;
24 | private int freqZero;
25 | private ISubGenerator currentGenerator;
26 | private ISubGenerator nextGenerator;
27 |
28 | public ToneGenerator(int sampleRate, int dataFreq)
29 | {
30 | this.sampleRate = sampleRate;
31 | this.freqOne = dataFreq - 100;
32 | this.freqZero = dataFreq + 100;
33 | this.currentGenerator = new SilenceGenerator();
34 | this.nextGenerator = null;
35 | SetWaveFormat(sampleRate, 1);
36 | }
37 |
38 | public void Silence()
39 | {
40 | this.nextGenerator = new SilenceGenerator();
41 | }
42 |
43 | public void SendANSam()
44 | {
45 | this.nextGenerator = new ANSamGenerator(sampleRate);
46 | }
47 |
48 | public void Repeat(bool sendPause, int[] bits)
49 | {
50 | this.nextGenerator = new RepeatGenerator(sampleRate, freqOne, freqZero, sendPause ? 500 : 0, bits);
51 | }
52 |
53 | public void PrepareForData(bool sendPreamble)
54 | {
55 | this.nextGenerator = new PrepareForDataGenerator(sampleRate, freqOne, freqZero, sendPreamble);
56 | }
57 |
58 | public void EnqueueBits(int[] bits)
59 | {
60 | currentGenerator.EnqueueBits(bits);
61 | }
62 |
63 | public override int Read(float[] samples, int offset, int sampleCount)
64 | {
65 | var numRead = currentGenerator.Generate(samples, offset, sampleCount);
66 | if (currentGenerator.IsDone)
67 | {
68 | if (nextGenerator != null)
69 | {
70 | currentGenerator = nextGenerator;
71 | nextGenerator = null;
72 | }
73 | else if (currentGenerator.ReadyForData)
74 | {
75 | currentGenerator = new DataGenerator(sampleRate, freqOne, freqZero, false);
76 | nextGenerator = null;
77 | }
78 | }
79 | return numRead;
80 | }
81 |
82 | }
83 |
84 | internal interface ISubGenerator
85 | {
86 | bool IsDone { get; }
87 | bool ReadyForData { get; }
88 | int Generate(float[] samples, int offset, int sampleCount);
89 | void EnqueueBits(int[] bits);
90 | }
91 |
92 | internal class SilenceGenerator : ISubGenerator
93 | {
94 | public bool IsDone { get { return true; } }
95 |
96 | public bool ReadyForData { get { return false; } }
97 |
98 | public int Generate(float[] samples, int offset, int sampleCount)
99 | {
100 | for (int i = 0; i < sampleCount; ++i)
101 | {
102 | samples[i + offset] = 0;
103 | }
104 | return sampleCount;
105 | }
106 |
107 | public void EnqueueBits(int[] bits) { }
108 | }
109 |
110 | internal class ANSamGenerator : ISubGenerator
111 | {
112 | private double freq2100;
113 | private double freq15;
114 | private int samplesPerInversion;
115 | private int sampleNum;
116 | private bool invert;
117 |
118 | public bool IsDone { get { return true; } }
119 |
120 | public bool ReadyForData { get { return false; } }
121 |
122 | public ANSamGenerator(int sampleRate)
123 | {
124 | this.freq2100 = 2 * Math.PI * 2100 / sampleRate;
125 | this.freq15 = 2 * Math.PI * 15 / sampleRate;
126 | this.samplesPerInversion = sampleRate * 9 / 20;
127 | this.sampleNum = 0;
128 | this.invert = false;
129 | }
130 |
131 | public int Generate(float[] samples, int offset, int sampleCount)
132 | {
133 | for (int i = 0; i < sampleCount; ++i)
134 | {
135 | double sample = Math.Cos(freq2100 * sampleNum) * (1 + 0.2 * Math.Cos(freq15 * sampleNum)) / 1.2;
136 | if (invert) sample = -sample;
137 | samples[i + offset] = (float)sample;
138 | ++sampleNum;
139 | if (sampleNum == samplesPerInversion)
140 | {
141 | sampleNum = 0;
142 | invert = !invert;
143 | }
144 | }
145 | return sampleCount;
146 | }
147 |
148 | public void EnqueueBits(int[] bits) { }
149 | }
150 |
151 | internal class RepeatGenerator : ISubGenerator
152 | {
153 | private const int NumRepeats = 5;
154 |
155 | private SilenceGenerator silenceGenerator;
156 | private DataGenerator dataGenerator;
157 | private int samplesPerBit;
158 | private int pauseLen;
159 | private int repetitions;
160 | private int[] bits;
161 |
162 | public bool IsDone { get { return pauseLen == 0 && dataGenerator.IsDone; } }
163 |
164 | public bool ReadyForData { get { return false; } }
165 |
166 | public RepeatGenerator(int sampleRate, int freqOne, int freqZero, int pauseLen, int[] bits)
167 | {
168 | this.silenceGenerator = new SilenceGenerator();
169 | this.dataGenerator = new DataGenerator(sampleRate, freqOne, freqZero, true);
170 | this.samplesPerBit = sampleRate / 300;
171 | this.pauseLen = sampleRate * pauseLen / 1000;
172 | this.repetitions = 0;
173 | this.bits = bits;
174 | }
175 |
176 | public int Generate(float[] samples, int offset, int sampleCount)
177 | {
178 | int sent = 0;
179 | if (pauseLen > 0)
180 | {
181 | sent = silenceGenerator.Generate(samples, offset, Math.Min(sampleCount, pauseLen));
182 | pauseLen -= sent;
183 | if (sent == sampleCount)
184 | {
185 | return sent;
186 | }
187 | }
188 |
189 | while (sent < sampleCount && repetitions < NumRepeats)
190 | {
191 | if (dataGenerator.IsDone)
192 | {
193 | dataGenerator.EnqueueBits(bits);
194 | }
195 | sent += dataGenerator.Generate(samples, offset + sent, sampleCount - sent);
196 | if (dataGenerator.IsDone)
197 | {
198 | ++repetitions;
199 | }
200 | }
201 | repetitions %= NumRepeats;
202 | return sent;
203 | }
204 |
205 | public void EnqueueBits(int[] bits) { }
206 | }
207 |
208 | internal class PrepareForDataGenerator : ISubGenerator
209 | {
210 | private int sampleRate;
211 | private int freqOne;
212 | private int freqZero;
213 | private DataGenerator dataGenerator;
214 | private SilenceGenerator silenceGenerator;
215 | private int pauseLen;
216 |
217 | public bool IsDone { get { return pauseLen == 0; } }
218 |
219 | public bool ReadyForData { get { return IsDone; } }
220 |
221 | public PrepareForDataGenerator(int sampleRate, int freqOne, int freqZero, bool sendPreamble)
222 | {
223 | this.sampleRate = sampleRate;
224 | this.freqOne = freqOne;
225 | this.freqZero = freqZero;
226 | if (sendPreamble)
227 | {
228 | this.dataGenerator = new DataGenerator(sampleRate, freqOne, freqZero, true);
229 | this.dataGenerator.EnqueueBits(new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 });
230 | }
231 | else
232 | {
233 | this.dataGenerator = null;
234 | }
235 | this.silenceGenerator = new SilenceGenerator();
236 | this.pauseLen = sampleRate * 75 / 1000;
237 | }
238 |
239 | public int Generate(float[] samples, int offset, int sampleCount)
240 | {
241 | int preambleSent = 0;
242 | if (dataGenerator != null)
243 | {
244 | preambleSent = dataGenerator.Generate(samples, offset, sampleCount);
245 | if (dataGenerator.IsDone)
246 | {
247 | dataGenerator = null;
248 | }
249 | }
250 | int toSend = Math.Min(sampleCount - preambleSent, pauseLen);
251 | int silenceSent = silenceGenerator.Generate(samples, offset + preambleSent, toSend);
252 | pauseLen -= silenceSent;
253 | return preambleSent + silenceSent;
254 | }
255 |
256 | public void EnqueueBits(int[] bits) { }
257 |
258 | }
259 |
260 | internal class DataGenerator : ISubGenerator
261 | {
262 | private int sampleRate;
263 | private double phaseDeltaOne;
264 | private double phaseDeltaZero;
265 | private double phase;
266 | private bool stopOnEnd;
267 | private int samplesPerBit;
268 | private int remainingSamples;
269 | private ConcurrentQueue bitQueue;
270 | private int currentBit;
271 |
272 | public bool IsDone { get { return bitQueue.IsEmpty && remainingSamples == 0; } }
273 |
274 | public bool ReadyForData { get { return false; } }
275 |
276 | public DataGenerator(int sampleRate, int freqOne, int freqZero, bool stopOnEnd)
277 | {
278 | this.sampleRate = sampleRate;
279 | this.phaseDeltaOne = 2 * Math.PI * freqOne / sampleRate;
280 | this.phaseDeltaZero = 2 * Math.PI * freqZero / sampleRate;
281 | this.phase = 0;
282 | this.stopOnEnd = stopOnEnd;
283 | this.samplesPerBit = sampleRate / 300;
284 | this.remainingSamples = 0;
285 | this.bitQueue = new ConcurrentQueue();
286 | this.currentBit = 1;
287 | }
288 |
289 | public int Generate(float[] samples, int offset, int sampleCount)
290 | {
291 | int sent = 0;
292 | while (sent < sampleCount)
293 | {
294 | if (remainingSamples == 0)
295 | {
296 | if (bitQueue.IsEmpty && stopOnEnd)
297 | {
298 | return sent;
299 | }
300 | int readBit;
301 | if (bitQueue.TryDequeue(out readBit))
302 | {
303 | currentBit = readBit;
304 | }
305 | remainingSamples = samplesPerBit;
306 | }
307 | double sample = Math.Cos(phase);
308 | samples[sent + offset] = (float)sample;
309 | phase += currentBit == 1 ? phaseDeltaOne : phaseDeltaZero;
310 | if (phase > Math.PI)
311 | {
312 | phase -= 2 * Math.PI;
313 | }
314 | --remainingSamples;
315 | ++sent;
316 | }
317 | return sent;
318 | }
319 |
320 | public void EnqueueBits(int[] bits)
321 | {
322 | foreach (var b in bits)
323 | {
324 | bitQueue.Enqueue(b);
325 | }
326 | }
327 | }
328 | }
329 |
--------------------------------------------------------------------------------
/SoftwareModem/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/diagram-modem.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jtarrio/SoftwareModem/c05bec8876d8113008d232d5f3165374845b4b6f/diagram-modem.png
--------------------------------------------------------------------------------