Added more clear description

Fixed issue #59
pull/69/head
Marcin Kondej 2018-12-29 03:18:27 +01:00
rodzic 71e7e23a0e
commit 121982a2c5
12 zmienionych plików z 147 dodań i 239 usunięć

1
.gitignore vendored
Wyświetl plik

@ -1,3 +1,2 @@
*.o
*.swp
fm_transmitter

Wyświetl plik

@ -1,44 +1,47 @@
# fm_transmitter
Use Raspberry Pi as FM transmitter. Works on any RPi board.
Use Raspberry Pi as FM transmitter. Works on any Raspberry Pi board.
This project uses the general clock output to produce frequency modulated radio communication. It is based on idea originaly posted here: [http://icrobotics.co.uk/wiki/index.php/Turning_the_Raspberry_Pi_Into_an_FM_Transmitter](http://icrobotics.co.uk/wiki/index.php/Turning_the_Raspberry_Pi_Into_an_FM_Transmitter), but does not use DMA controller in order to distribute samples to output (clock generator), so sound quality is worse as in PiFm project and only mono transmition is available but this makes possible to run it on all kind of boards.
## How to use it
To compile this project use commands below:
To use this project You will have to buid it. First, clone this repository, then use "make" command as shown below:
```
sudo apt-get install make gcc g++
git clone https://github.com/markondej/fm_transmitter
cd fm_transmitter
make
```
Then you can use it by typing:
After successful build You can start transmitting by typing:
```
sudo ./fm_transmitter [-f frequency] [-r] filename
sudo ./fm_transmitter -f 102.0 acoustic_guitar_duet.wav
```
where:
* -f frequency - Specifies the frequency in MHz, default is 100.0
* -r - Loops the file
* filename - WAVE file name
Where:
* -f 102.0 - Specifies the frequency in MHz, if not passed default is 100.0
* acoustic_guitar_duet.wav - Sample WAVE file, You can use your own
### WAVE Files
You can open uncompressed WAVE (.wav) files or read audio data from stdin, eg.:
### Supported audio files
You can transmitt uncompressed WAVE (.wav) files directly or read audio data from stdin, eg.:
```
sox star_wars.wav -r 22050 -c 1 -b 16 -t wav - | sudo ./fm_transmitter -f 100.6 -
```
Notice only uncompressed WAVE files are supported. If You expire "corrupted data" error try converting file, eg. by using SoX:
```
sox my-audio.mp3 -r 22050 -c 1 -b 16 -t wav my-converted-audio.wav
sudo ./fm_transmitter -f 100.6 my-converted-audio.wav
```
### USB microphone
To use a USB sound card microphone input use arecord, eg.:
```
arecord -D hw:1,0 -c1 -d 0 -r 22050 -f S16_LE | sudo ./fm_transmitter -f 100.6 -
```
In case of performance dropdown use ```plughw:1,0``` instead of ```hw:1,0```.
In case of performance drop down use ```plughw:1,0``` instead of ```hw:1,0```.
## Legal note
Please keep in mind that transmitting on certain frequencies without special permissions may be illegal in your country.
## New features
* works on RPi 1, 2 and 3
* works on any Raspberry Pi model
* reads mono and stereo files
* reads data from stdin
* based on threads
Included sample audio was created by [graham_makes](https://freesound.org/people/graham_makes/sounds/449409/) and published on [freesound.org](https://freesound.org/)

Plik binarny nie jest wyświetlany.

Wyświetl plik

@ -1,44 +0,0 @@
/*
fm_transmitter - use Raspberry Pi as FM transmitter
Copyright (c) 2015, Marcin Kondej
All rights reserved.
See https://github.com/markondej/fm_transmitter
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef AUDIO_FORMAT_H
#define AUDIO_FORMAT_H
struct AudioFormat
{
unsigned short channels;
unsigned short bitsPerSample;
unsigned sampleRate;
};
#endif // AUDIO_FORMAT_H

Wyświetl plik

@ -44,9 +44,9 @@ class ErrorReporter : public exception
{
public:
explicit ErrorReporter(string message);
virtual ~ErrorReporter() throw();
virtual ~ErrorReporter() throw();
virtual const char* what() const throw();
virtual const char* what() const throw();
protected:
string errorMessage;
};

Wyświetl plik

@ -31,25 +31,17 @@
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include "wave_reader.h"
#include "transmitter.h"
#include <cstdlib>
#include <csignal>
#include <iostream>
#include <unistd.h>
using namespace std;
bool stop = false;
Transmitter* transmitter = NULL;
AudioFormat* getFormat(string filename) {
stop = false;
WaveReader* reader = new WaveReader(filename, stop);
AudioFormat* format = reader->getFormat();
delete reader;
return format;
}
void sigIntHandler(int sigNum)
{
if (transmitter != NULL) {
@ -64,23 +56,23 @@ int main(int argc, char** argv)
double frequency = 100.0;
bool loop = false;
string filename;
bool showUsage = true;
for (int i = 1; i < argc; i++) {
if (string("-f") == argv[i]) {
if (i < argc - 1) {
frequency = ::atof(argv[i + 1]);
i++;
}
} else if (string("-r") == argv[i]) {
loop = true;
} else {
if (i == argc - 1) {
showUsage = false;
filename = argv[i];
}
int opt;
while ((opt = getopt(argc, argv, "rf:")) != -1) {
switch (opt) {
case 'r':
loop = true;
break;
case 'f':
frequency = ::atof(optarg);
break;
}
}
if (optind < argc) {
filename = argv[optind];
showUsage = false;
}
if (showUsage) {
cout << "Usage: " << argv[0] << " [-f frequency] [-r] FILE" << endl;
return 0;
@ -90,19 +82,13 @@ int main(int argc, char** argv)
try {
transmitter = Transmitter::getInstance();
if (filename != "-") {
AudioFormat* format = getFormat(filename);
cout << "Playing: " << filename << ", "
<< format->sampleRate << " Hz, "
<< format->bitsPerSample << " bits, "
<< ((format->channels > 0x01) ? "stereo" : "mono") << endl;
delete format;
} else {
cout << "Playing: STDIN" << endl;
}
transmitter->play(filename, frequency, loop);
WaveReader reader(filename != "-" ? filename : string(), stop);
PCMWaveHeader header = reader.getHeader();
cout << "Playing: " << reader.getFilename() << ", "
<< header.sampleRate << " Hz, "
<< header.bitsPerSample << " bits, "
<< ((header.channels > 0x01) ? "stereo" : "mono") << endl;
transmitter->play(&reader, frequency, 0, loop);
} catch (exception &error) {
cout << "Error: " << error.what() << endl;
return 1;

Wyświetl plik

@ -1,22 +1,24 @@
CFLAGS += -Wall -fexceptions -pthread -lm -O3 -fpermissive -fno-strict-aliasing
FLAGS = -Wall -fexceptions -pthread -O3 -fpermissive -fno-strict-aliasing
INCLUDES = -I/opt/vc/include -L/opt/vc/lib
LIBS = -lm -lbcm_host
TARGET = fm_transmitter
CPP=$(CCPREFIX)g++
all: main.o error_reporter.o wave_reader.o transmitter.o
$(CPP) $(CFLAGS) -o $(TARGET) main.o error_reporter.o wave_reader.o transmitter.o
$(CPP) $(FLAGS) $(INCLUDES) $(LIBS) -o $(TARGET) main.o error_reporter.o wave_reader.o transmitter.o
wave_reader.o: wave_reader.cpp wave_reader.h
$(CPP) $(CFLAGS) -c wave_reader.cpp
$(CPP) $(FLAGS) $(INCLUDES) $(LIBS) -c wave_reader.cpp
error_reporter.o: error_reporter.cpp error_reporter.h
$(CPP) $(CFLAGS) -c error_reporter.cpp
$(CPP) $(FLAGS) $(INCLUDES) $(LIBS) -c error_reporter.cpp
transmitter.o: transmitter.cpp transmitter.h
$(CPP) $(CFLAGS) -c transmitter.cpp
$(CPP) $(FLAGS) $(INCLUDES) $(LIBS) -c transmitter.cpp
main.o: main.cpp
$(CPP) $(CFLAGS) -c main.cpp
$(CPP) $(FLAGS) $(INCLUDES) $(LIBS) -c main.cpp
clean:
rm *.o

Plik binarny nie jest wyświetlany.

Wyświetl plik

@ -32,16 +32,15 @@
*/
#include "transmitter.h"
#include "wave_reader.h"
#include "error_reporter.h"
#include <bcm_host.h>
#include <sstream>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
using std::ostringstream;
using std::vector;
#define GPIO_BASE 0x00200000
#define CLK0_BASE 0x00101070
@ -51,40 +50,14 @@ using std::ostringstream;
#define ACCESS(base, offset) *(volatile unsigned*)((int)base + offset)
#define ACCESS64(base, offset) *(volatile unsigned long long*)((int)base + offset)
bool Transmitter::transmitting = false;
bool Transmitter::restart = false;
unsigned Transmitter::clockDivisor = 0;
unsigned Transmitter::frameOffset = 0;
vector<float>* Transmitter::buffer = NULL;
void* Transmitter::peripherals = NULL;
Transmitter::Transmitter()
{
bool isBcm2835 = true;
FILE* pipe = popen("uname -m", "r");
if (pipe) {
char buffer[64];
string machine = "";
while (!feof(pipe)) {
if (fgets(buffer, 64, pipe)) {
machine += buffer;
}
}
pclose(pipe);
machine = machine.substr(0, machine.length() - 1);
if (machine != "armv6l") {
isBcm2835 = false;
}
}
int memFd;
if ((memFd = open("/dev/mem", O_RDWR | O_SYNC)) < 0) {
throw ErrorReporter("Cannot open /dev/mem (permission denied)");
}
peripherals = mmap(NULL, 0x002FFFFF, PROT_READ | PROT_WRITE, MAP_SHARED, memFd, isBcm2835 ? 0x20000000 : 0x3F000000);
peripherals = mmap(NULL, bcm_host_get_peripheral_size(), PROT_READ | PROT_WRITE, MAP_SHARED, memFd, bcm_host_get_peripheral_address());
close(memFd);
if (peripherals == MAP_FAILED) {
throw ErrorReporter("Cannot obtain access to peripherals (mmap error)");
@ -93,7 +66,7 @@ Transmitter::Transmitter()
Transmitter::~Transmitter()
{
munmap(peripherals, 0x002FFFFF);
munmap(peripherals, bcm_host_get_peripheral_size());
}
Transmitter* Transmitter::getInstance()
@ -102,7 +75,7 @@ Transmitter* Transmitter::getInstance()
return &instance;
}
void Transmitter::play(string filename, double frequency, bool loop)
void Transmitter::play(WaveReader* reader, double frequency, unsigned char dmaChannel, bool loop)
{
if (transmitting) {
throw ErrorReporter("Cannot play, transmitter already in use");
@ -111,40 +84,45 @@ void Transmitter::play(string filename, double frequency, bool loop)
transmitting = true;
forceStop = false;
WaveReader* reader = new WaveReader(filename != "-" ? filename : string(), forceStop);
AudioFormat* format = reader->getFormat();
PCMWaveHeader header = reader->getHeader();
unsigned bufferFrames = (unsigned)((unsigned long long)header.sampleRate * BUFFER_TIME / 1000000);
vector<float>* frames = reader->getFrames(bufferFrames, forceStop);
if (frames == NULL) {
return;
}
bool eof = frames->size() < bufferFrames;
vector<float>* buffer = frames;
clockDivisor = (unsigned)((500 << 12) / frequency + 0.5);
unsigned bufferFrames = (unsigned)((unsigned long long)format->sampleRate * BUFFER_TIME / 1000000);
unsigned frameOffset = 0;
unsigned clockDivisor = (unsigned)((500 << 12) / frequency + 0.5);
bool restart = false;
frameOffset = 0;
restart = false;
void* params[8] = {
peripherals,
(void*)(unsigned*)&buffer,
(void*)(unsigned*)&frameOffset,
(void*)(unsigned*)&clockDivisor,
(void*)(unsigned*)&transmitting,
(void*)(unsigned*)&restart,
(void*)(unsigned*)&dmaChannel,
(void*)(unsigned*)&header.sampleRate
};
pthread_t thread;
int returnCode = pthread_create(&thread, NULL, &Transmitter::transmit, (void*)&params);
if (returnCode) {
delete frames;
ostringstream oss;
oss << "Cannot create new thread (code: " << returnCode << ")";
throw ErrorReporter(oss.str());
}
usleep(BUFFER_TIME / 2);
bool isError = false;
string errorMessage;
try {
vector<float>* frames = reader->getFrames(bufferFrames, forceStop);
if (frames == NULL) {
delete format;
delete reader;
return;
}
eof = frames->size() < bufferFrames;
buffer = frames;
pthread_t thread;
void* params = (void*)&format->sampleRate;
int returnCode = pthread_create(&thread, NULL, &Transmitter::transmit, params);
if (returnCode) {
delete reader;
delete format;
delete frames;
ostringstream oss;
oss << "Cannot create new thread (code: " << returnCode << ")";
throw ErrorReporter(oss.str());
}
usleep(BUFFER_TIME / 2);
while (!forceStop) {
while (!eof && !forceStop) {
if (buffer == NULL) {
@ -178,72 +156,73 @@ void Transmitter::play(string filename, double frequency, bool loop)
forceStop = true;
}
}
transmitting = false;
pthread_join(thread, NULL);
} catch (ErrorReporter &error) {
delete reader;
delete format;
throw error;
} catch (ErrorReporter &error) {
errorMessage = error.what();
isError = true;
}
delete reader;
delete format;
}
transmitting = false;
pthread_join(thread, NULL);
if (isError) {
throw ErrorReporter(errorMessage);
}
}
void* Transmitter::transmit(void* params)
{
void* peripherals = ((void**)params)[0];
vector<float>** buffer = (vector<float>**)((void**)params)[1];
unsigned* frameOffset = (unsigned*)((void**)params)[2], clockDivisor = (unsigned*)((void**)params)[3];
bool* transmitting = (bool*)((void**)params)[4], restart = (bool*)((void**)params)[5];
unsigned char dmaChannel = *(unsigned char*)((void**)params)[6];
unsigned sampleRate = *(unsigned*)((void**)params)[7];
unsigned long long current, start, playbackStart;
unsigned offset, length, temp;
unsigned offset, length, prevOffset;
vector<float>* frames = NULL;
float* data;
float value;
#ifndef NO_PREEMP
float prevValue = 0.0;
#endif
unsigned sampleRate = *(unsigned*)(params);
#ifndef NO_PREEMP
float preemp = 0.75 - 250000.0 / (float)(sampleRate * 75);
#endif
ACCESS(peripherals, GPIO_BASE) = (ACCESS(peripherals, GPIO_BASE) & 0xFFFF8FFF) | (0x01 << 14);
ACCESS(peripherals, CLK0_BASE) = (0x5A << 24) | (0x01 << 9) | (0x01 << 4) | 0x06;
playbackStart = ACCESS64(peripherals, TCNT_BASE);
current = playbackStart;
current = ACCESS64(peripherals, TCNT_BASE);
playbackStart = current;
while (transmitting) {
while (*transmitting) {
start = current;
while ((buffer == NULL) && transmitting) {
while ((*buffer == NULL) && *transmitting) {
usleep(1);
current = ACCESS64(peripherals, TCNT_BASE);
}
if (!transmitting) {
if (!*transmitting) {
break;
}
if (restart) {
if (*restart) {
playbackStart = current;
start = current;
restart = false;
*restart = false;
}
frames = buffer;
frameOffset = (current - playbackStart) * (sampleRate) / 1000000;
buffer = NULL;
frames = *buffer;
*frameOffset = (current - playbackStart) * (sampleRate) / 1000000;
*buffer = NULL;
offset = (current - start) * (sampleRate) / 1000000;
length = frames->size();
data = &(*frames)[0];
offset = 0;
while (true) {
temp = offset;
if (offset >= length) {
offset -= length;
break;
}
prevOffset = offset;
value = data[offset];
#ifndef NO_PREEMP
@ -251,8 +230,8 @@ void* Transmitter::transmit(void* params)
value = (value < -1.0) ? -1.0 : ((value > 1.0) ? 1.0 : value);
#endif
ACCESS(peripherals, CLK0DIV_BASE) = (0x5A << 24) | ((clockDivisor) - (int)(round(value * 16.0)));
while (temp >= offset) {
ACCESS(peripherals, CLK0DIV_BASE) = (0x5A << 24) | ((*clockDivisor) - (int)(round(value * 16.0)));
while (offset == prevOffset) {
asm("nop");
current = ACCESS64(peripherals, TCNT_BASE);
offset = (current - start) * (sampleRate) / 1000000;

Wyświetl plik

@ -34,11 +34,7 @@
#ifndef TRANSMITTER_H
#define TRANSMITTER_H
#include "error_reporter.h"
#include "audio_format.h"
#include <vector>
using std::vector;
#include "wave_reader.h"
#define BUFFER_TIME 1000000
@ -48,21 +44,15 @@ class Transmitter
{
public:
virtual ~Transmitter();
void play(string filename, double frequency, bool loop);
void stop();
static Transmitter* getInstance();
void play(WaveReader* reader, double frequency, unsigned char dmaChannel, bool loop);
void stop();
private:
Transmitter();
bool forceStop, eof;
static void* peripherals;
static vector<float>* buffer;
static bool transmitting, restart;
static unsigned frameOffset, clockDivisor;
static void* transmit(void* params);
void* peripherals;
bool forceStop, transmitting;
};
#endif // TRANSMITTER_H

Wyświetl plik

@ -1,4 +1,4 @@
#n/*
/*
fm_transmitter - use Raspberry Pi as FM transmitter
Copyright (c) 2018, Marcin Kondej
@ -34,16 +34,15 @@
#include "wave_reader.h"
#include "error_reporter.h"
#include <sstream>
#include <string.h>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
using std::ostringstream;
using std::exception;
WaveReader::WaveReader(string filename, bool &forceStop) :
filename(filename), currentFrameOffset(0), headerOffset(0)
filename(filename), headerOffset(0), currentFrameOffset(0)
{
char* headerData = (char*)((void*)&header);
ostringstream oss;
@ -78,7 +77,7 @@ WaveReader::WaveReader(string filename, bool &forceStop) :
throw ErrorReporter(oss.str());
}
readData(header.subchunk1Size, true, forceStop, headerData, headerOffset);
readData(header.subchunk1Size, true, forceStop, headerData);
if ((header.audioFormat != WAVE_FORMAT_PCM) ||
(header.byteRate != (header.bitsPerSample >> 3) * header.channels * header.sampleRate) ||
@ -172,7 +171,7 @@ vector<float>* WaveReader::getFrames(unsigned frameCount, bool &forceStop) {
bytesPerFrame = (header.bitsPerSample >> 3) * header.channels;
bytesToRead = frameCount * bytesPerFrame;
bytesLeft = header.subchunk2Size - currentFrameOffse;
bytesLeft = header.subchunk2Size - currentFrameOffset;
if (bytesToRead > bytesLeft) {
bytesToRead = bytesLeft - bytesLeft % bytesPerFrame;
frameCount = bytesToRead / bytesPerFrame;
@ -216,7 +215,7 @@ vector<float>* WaveReader::getFrames(unsigned frameCount, bool &forceStop) {
bool WaveReader::setFrameOffset(unsigned frameOffset) {
if (fileDescriptor != STDIN_FILENO) {
currentFrameOffset = frameOffset * (header.bitsPerSample >> 3) * header.channels;
if (lseek(fileDescriptor, dataOffset + currentFrameOffse, SEEK_SET) == -1) {
if (lseek(fileDescriptor, dataOffset + currentFrameOffset, SEEK_SET) == -1) {
return false;
}
}
@ -228,11 +227,7 @@ string WaveReader::getFilename()
return fileDescriptor != STDIN_FILENO ? filename : "STDIN";
}
AudioFormat* WaveReader::getFormat()
PCMWaveHeader WaveReader::getHeader()
{
AudioFormat* format = new AudioFormat;
format->channels = header.channels;
format->sampleRate = header.sampleRate;
format->bitsPerSample = header.bitsPerSample;
return format;
return header;
}

Wyświetl plik

@ -34,10 +34,9 @@
#ifndef WAVE_READER_H
#define WAVE_READER_H
#include "pcm_wave_header.h"
#include <string>
#include <vector>
#include "audio_format.h"
#include "pcm_wave_header.h"
using std::vector;
using std::string;
@ -47,18 +46,17 @@ class WaveReader
public:
WaveReader(string filename, bool &forceStop);
virtual ~WaveReader();
AudioFormat* getFormat();
string getFilename();
PCMWaveHeader getHeader();
vector<float>* getFrames(unsigned frameCount, bool &forceStop);
bool setFrameOffset(unsigned frameOffset);
private:
vector<char>* readData(unsigned bytesToRead, bool headerBytes, bool &forceStop, char* headerData);
string filename;
PCMWaveHeader header;
unsigned dataOffset, headerOffset, currentFrameOffset;
int fileDescriptor;
vector<char>* readData(unsigned bytesToRead, bool headerBytes, bool &forceStop, char* headerData);
string getFilename();
};
#endif // WAVE_READER_H