Full Code of iafan/Hacksby for AI

master 2fbfa34f2263 cached
20 files
63.6 KB
21.2k tokens
1 requests
Download .txt
Repository: iafan/Hacksby
Branch: master
Commit: 2fbfa34f2263
Files: 20
Total size: 63.6 KB

Directory structure:
gitextract_yn7l7n2u/

├── .gitignore
├── MIT-LICENSE.txt
├── README.md
├── bin/
│   ├── .gitignore
│   ├── draw-fft.pl
│   ├── furby-decode.pl
│   ├── furby-listen.bat
│   ├── furby-send.bat
│   ├── furby-send.pl
│   └── win32/
│       └── README.md
├── lib/
│   └── Furby/
│       ├── Audio.pm
│       ├── Command/
│       │   └── Dictionary.pm
│       ├── Command.pm
│       └── Packet.pm
└── src/
    ├── .gitignore
    ├── dsplay/
    │   ├── README.md
    │   └── dsplay.dpr
    └── rec_stdout/
        ├── README.md
        ├── rec_stdout.dpr
        └── test_rec_stdout.pl

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
~*
~*.*

================================================
FILE: MIT-LICENSE.txt
================================================
Copyright (c) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

================================================
FILE: README.md
================================================
About Hacksby
=============

### Hacksby = Hack-a-Furby project

Hasbro's Furby toy (year 2012 model) uses audio protocol to communicate with other
nearby Furbys and with the official 'Furby' applications for iOS and Android.

This project is an educational attempt to analyze and re-create the audio protocol
and communicate with Furby using computer in a search for some easter eggs or
otherwise undocumented features.

At its current state, the project includes:

 1. Description on the audio protocol (see below)
 2. [An incomplete] description of various Furby commands
 3. An Perl library and scripts that can generate and play WAV files
    with arbitrary commands (to talk to Furby)
 4. A script that can decode commands from a provided audio stream
    (to interpret Furby's responses).


Disclaimer
==========

### This information is provided for personal educational purposes only.
### The author does not guarantee the accuracy of this information.
### By using the provided information, libraries or software, you solely take the risks of damaging your hardware or your ears.

See `MIT-LICENSE.txt` for more information.


Audio Protocol
==============

Furby audio protocol uses high-pitch frequencies to encode special commands (command
is an integer number in [0..1023] range). Furby decodes such commands using its built-in
microphone and may respond to some of them. When an event occurs (Furby pronounces
some phrase or performs an action), he can also emit such a command in addition to
an audible sound. This feature is used in the official application 'Translator'
mode, when it recognizes what Furby said and provides an instant translation.

Each command is divided into two packages with 0.5 sec gap in between.
The first package carries the higher 5 bits of the command number, and the second one
carries the lower 5 bits. 

If you record the responce from Furby or from iOS application and view its spectrum,
You will see that each packet looks like this: 

    2  --------##--------------------------------------##----
    3  ----##----------------------##--##----------##--------
    X  --##--##--##--##--##--##--##--##--##--##--##--##--##--
    1  --------------------##--------------##----------------
    0  ------------##--##------##--------------##------------

The total length of the packet is 0.5 second. Here `X` is a central frequency (17500 Hz),
and `0`, `1`, `2` and `3` are the data frequencies. The distance between each adjacent frequency
is approx. 557 Hz.

The central frequency carries no data and was likely introduce to aid in packet decoding.
The other four frequencies carry data. If one writes down the packet depicted above as a number in the
quaternary numeral system using 0, 1, 2, 3 digits after the name of each frequency, he would
get the following number: `3200 1033 1032` (for clarity, the number is separated into three quadruplets
each representing a byte).

The first byte, `3200`, if written in the binary form, will look like this: `11 1 00000`, where the first
two bits are always `11`, the second bit will be `0` for the first packet and `1` for the second, and
the remainder `00000` represents the 5 data bits themselves.

The second byte, `1033`, depends on the data bits and is used as a checksum (original algorithm is unknown).
The `lib/Furby/Packet.pm` file lists all 64 checksums (32 for the first packet and 32 for the second) needed
to reconstruct any arbitrary command in [0..1023] range.

The last byte, `1032`, is always the same.

To eliminate ticks when playing back such audio packets, the original waveform uses smooth changes in
frequency between each data tone. Also, such frequencies are not noticable if combined with pretty loud
audible responses Furby generates at the same time.


Commands
========

Based on initial research, a list of known commands (or events) and their descriptions is provided in
`lib/Furby/Commands.pm` and `lib/Furby/Dictionary.pm`. The list is incomplete and the already existing
descriptions may be inaccurate.

The task of interpreting the meaning of the commands is complicated further by the fact that Furby
can be in one of 6 personalities, and depending on its current personality, may respond to commands
differently and produce different events on its own.

### Furby Personality

When Furby understands a command, it will respond back with his current personality id.
Known personalities (as listed in official Android application) are:

  1. Princess (command id `901`) — a lovable one
  2. Diva (command id `902`) — a musical one
  3. Warrior (command id `903`) — also known as 'evil'
  4. Joker (command id = `904`) — also known ad 'mad' or 'freaky'
  5. Gossip Queen (command id `905`) — a chatty one

There is no known way to instantly change Furby's personality via some special command. Sending a command
with the personality id back to Furby seems to produce no effect.

### Communication Mode

When Furby chats or performs any action, it will ignore any commands sent to him.
So one needs to ensure Furby is listenting before sending any command. Luckily, there's command `820`
which will put him into such listening mode for one minute (during this period, Furby just stay awake
and listen for other commands). This comamnd is used in the official applications and is sent every 40
seconds or so to keep Furby listen and stop doing silly things.

Unfortunately, even if one sends this command periodically, Furby will go into deep sleep mode after
10 minutes of inactivity. The only way to prevent it from sleep is turning or flippng Furby periodically
so that its orientation sensor detects the movement.

Tools
=====

Tools are located in `bin` directory.

### Send Commands to Furby

**CAUTION: setting the volume too high while playing back Furby commands may damage your ears!**

Put your Furby near the speaker connected to your computer (or connect an earbud to a headphone jack
and put it in front of Furby). Turn the volume all the way down. Wake up Furby and wait till it listens quietly.
Run the command below:

    perl furby-send.pl 350

Turn the volume up a little and run the command again to see if Furby recognizes it
(he should chew and then say something like "mmm, yum!"). If it doesn't, turn the volume up a bit and repeat
the procedure until it does.

#### Troubleshooting

If you can hear a discomforting high-pitch noise when the command plays but Furby doesn't repsond,
then something is wrong. Try putting Furby closer to the speaker or the earbud and make sure Furby doesn't
do anything on his own while you play back the command. Normally, Furby should pick up the command even if
you are not hearing it yet.

#### Interactive Mode

You can also run the tool in interactive mode:

    perl furby-send.pl 350 --interactive

After playing back the first command (`350`), the script will wait for your input. You can just press Enter to
play the next command in the range, or input a command number to play, or input anything else that doesn't
evaluate to a number (for example, `r`) to repeat the last command. This mode will allow you to explore the
Furby reactions to different commands.

The generated WAV file is saved as `out.wav` in the current directory. Under Windows, the playback is performed
using the provided command-line utility (`bin/win32/dsplay.exe`). Under Unix / Mac, an attempt to use
already existing console players is used (but not tested).


### Listen and Decode Furby Commands

The provided `furby-decode.pl` decodes the RAW PCM data from STDIN and displays any commands it decodes.
The only supported format is 44.1KHz mono 16bit signed PCM format.

You can pre-record a WAV file using your microphone and then decode it using this tool like this:

    perl furby-decode.pl < record.wav

or pipe in PCM data from a streaming application or virtual device. Under Windows, a binary tool is included 
(`bin/win32/rec_stdout.exe`) which records data from a default input source and constantly streams it to STDOUT.
You can use it like this:

    win32\rec_stdout.exe | perl furby-decode.pl

or just run

    furby-listen.bat

Before you run this command, make sure you have a microphone plugged in, that it is selected in Sound settings
as a default capturing device and put your microphone close to Furby.

The sound capture hasn't been tested on platforms other than Windows.

#### Troubleshooting

Some microphones (especially the ones integrated into web cameras) use a low-pass filter that would essentially
wipe out all frequencies that are used to transmit commands. If your decoding doesn't work, try recording
the audio sample into the 44.1KHz mono 16bit signed PCM WAV file (touch Furby's head or tum to make sure it responds
to your interaction and thus emits an event command), then open the file in a sound editor like Audacity,
make sure the audio format is correct, switch to a spectrum view and see if there are any frequencies recorded
around the 17.5KHz range (you will clearly see if there are command packets there).


### Feedback

Feedback and any further research results are always welcome.


================================================
FILE: bin/.gitignore
================================================
out.*


================================================
FILE: bin/draw-fft.pl
================================================
#!/usr/bin/perl

# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby

use strict;

# only raw 16bit signed PCM data is supported

use GD;
use Math::FFT;

my $filename = $ARGV[0];

if ($filename eq '') {
    print "Usage: perl $0 filename.raw\n";
    exit(1);
}

if (!-f $filename) {
    print "File '$filename' doesn't exist\n";
    exit(1);
}

my $base_freq = {
    '0' => 16386,
    '1' => 16943,
    'X' => 17500, # base frequency, used to construct raw commands (delta is approx 557 Hz) // was 17498 with 556 Hz delta
    '3' => 18057,
    '2' => 18614,
};

my $allowed_deviation = abs($base_freq->{'X'} - $base_freq->{'1'}) * 0.2;

my $buffer;
my $read_block_size = 10000;
my $sample_rate = 44100;
my $size_in_samples = 256;
my $expand_index = 5;
my $max_image_width = 10000;

my $fft_min_freq = 0;
my $fft_max_freq = $sample_rate / 2;
my $fft_spectrum_size = int($size_in_samples / 2) + 1;
my $fft_freq_delta = ($fft_max_freq - $fft_min_freq) / ($fft_spectrum_size - 1);

my $spectrum_first_idx = int($base_freq->{'0'} / $fft_freq_delta) - $expand_index;
$spectrum_first_idx = 0 if $spectrum_first_idx < 0;

my $spectrum_last_idx = int(($base_freq->{'2'} + $fft_freq_delta / 2) / $fft_freq_delta) + $expand_index;
$spectrum_last_idx = $fft_spectrum_size - 1 if $spectrum_first_idx > $fft_spectrum_size - 1;

my $image_height = $spectrum_last_idx - $spectrum_first_idx + 1;

my @spectrum_frequencies;
for my $y ($spectrum_first_idx..$spectrum_last_idx) {
    $spectrum_frequencies[$y] = $fft_min_freq + $y * $fft_freq_delta;
}

my $image_width = int((-s $filename) / ($size_in_samples * 2));
if ($image_width > $max_image_width) {
    $image_width = $max_image_width;
    print "Image would be too big; it will be trimmed to first $max_image_width spectrum pxiels\n";
}

my $image = new GD::Image($image_width, $image_height, 1);

my $base_freq_colors = {
    '0' => $image->colorResolve(255,   0, 255),
    '1' => $image->colorResolve(  0, 204, 255),
    'X' => $image->colorResolve(255,   0,   0),
    '3' => $image->colorResolve(  0, 255,   0),
    '2' => $image->colorResolve(255, 255,   0),
};

open(IN, $filename);
#sysread(IN, $_, 56); # skip RIFF header
read_from_handle(*IN);
close(IN);

my $x = 0;

my @samples;
my $buffer_leftover;
sub read_from_handle {
    my $handle = shift;
    while ((my $n = sysread($handle, $buffer, $read_block_size)) > 0) {
        #print "Read $n bytes\n";
        $buffer = $buffer_leftover.$buffer if $buffer_leftover; # prepend leftover byte, if any
        while (length($buffer) >= 2) {
            my $sample = unpack('s<', substr($buffer, 0, 2, ''));
            push(@samples, $sample);
            if ($size_in_samples == @samples) {
                analyze_samples();
                undef @samples;

                $x++;
                last if $x > $max_image_width - 1;
            }
        }
        $buffer_leftover = $buffer; # potentially there can be a single byte that we need to preserve for next iteration
    }
}

sub analyze_samples {
    my $fft = new Math::FFT(\@samples);
    my $spectrum = $fft->spctrm(window => 'hann');

    my $avg = 0;
    my $max = 0;
    my $max_y = -1;
    my $freq = 0;
    for my $y ($spectrum_first_idx..$spectrum_last_idx) {
        $avg += $spectrum->[$y];
        if ($spectrum->[$y] > $max) {
            $max = $spectrum->[$y];
            $max_y = $y;
            $freq = $spectrum_frequencies[$y];
        }
    }
    $avg = $avg / $fft_spectrum_size;
    my $contrast = ($avg == 0) ? $fft_spectrum_size : $max / $avg;

    my $known_frequency_key;
    foreach my $key (keys %$base_freq) {
        if (abs($base_freq->{$key} - $freq) < $allowed_deviation) {
            $known_frequency_key = $key;
            last;
        }
    }

    for my $y ($spectrum_first_idx..$spectrum_last_idx) {
        my $color = $max > 0 ? int($spectrum->[$y] / $max * 255) : 0;
        $color = 255 if $color > 255;
        #$color = int($color * 0.5);
        if ($contrast < ($fft_spectrum_size / 3.5)) {
           $color = $color * 0.2;
           $color = $image->colorResolve($color, $color, $color)
        } else {
            $color = ($y == $max_y) ? $image->colorResolve(255, 255, 255) : $image->colorResolve($color, $color, $color);
            if (defined $known_frequency_key && ($y == $max_y)) {
                $color = $base_freq_colors->{$known_frequency_key};
            }
        }
        $image->setPixel($x, $image_height - 1 - ($y - $spectrum_first_idx), $color);
    }
}

print "Saving out.png...\n";
open(OUT, ">out.png");
binmode OUT;
print OUT $image->png;
close OUT;


================================================
FILE: bin/furby-decode.pl
================================================
#!/usr/bin/perl

# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby

use strict;

# only raw 16bit signed PCM data is supported

BEGIN {
    use File::Spec::Functions qw(rel2abs catfile);
    use File::Basename;
    unshift(@INC, catfile(dirname(rel2abs($0)), '../lib'));
}

use Math::FFT;

use Furby::Audio;
use Furby::Command;
use Furby::Packet;

$| = 1; # prevent STDOUT buffering

$SIG{INT} = sub {
    print "SIGINT caught, stopping...\n";
    exit(2);
};

my $central_freq = Furby::Audio::base_freq('X');
my $next_to_central_freq = Furby::Audio::base_freq('1');
my $lowest_freq = Furby::Audio::base_freq('0');
my $highest_freq = Furby::Audio::base_freq('2');

my $allowed_deviation = abs($central_freq - $next_to_central_freq) * 0.2;

my $buffer;
my $read_block_size = 10000;
my $sample_rate = 44100;
my $size_in_samples = 256;
my $expand_index = 5;
my $contrast_ratio = 3.5;

my $fft_min_freq = 0;
my $fft_max_freq = $sample_rate / 2;
my $fft_spectrum_size = int($size_in_samples / 2) + 1;
my $fft_freq_delta = ($fft_max_freq - $fft_min_freq) / ($fft_spectrum_size - 1);

my $spectrum_first_idx = int($lowest_freq / $fft_freq_delta) - $expand_index;
$spectrum_first_idx = 0 if $spectrum_first_idx < 0;

my $spectrum_last_idx = int(($highest_freq + $fft_freq_delta / 2) / $fft_freq_delta) + $expand_index;
$spectrum_last_idx = $fft_spectrum_size - 1 if $spectrum_first_idx > $fft_spectrum_size - 1;

my @spectrum_frequencies;
for my $y ($spectrum_first_idx..$spectrum_last_idx) {
    $spectrum_frequencies[$y] = $fft_min_freq + $y * $fft_freq_delta;
}

my $char_buffer;
my $char = undef;
my $prev_was_X = undef;
my $packet1 = -1;

my $filename = $ARGV[0];

my $use_stdin = ($filename eq '');

if ($use_stdin) {
    my $h = *STDIN;
    while (1) {
        read_from_handle($h);
    }
} else {
    if (!-f $filename) {
        print "File '$filename' doesn't exist\n";
        exit(1);
    }
    open(IN, $filename);
    read_from_handle(*IN);
    close(IN);
}

my @samples;
my $buffer_leftover;
sub read_from_handle {
    my $handle = shift;
    while ((my $n = sysread($handle, $buffer, $read_block_size)) > 0) {
        #print "Read $n bytes\n";
        $buffer = $buffer_leftover.$buffer if $buffer_leftover; # prepend leftover byte, if any
        while (length($buffer) >= 2) {
            my $sample = unpack('s<', substr($buffer, 0, 2, ''));
            push(@samples, $sample);
            if ($size_in_samples == @samples) {
                analyze_samples();
                undef @samples;
            }
        }
        $buffer_leftover = $buffer; # potentially there can be a single byte that we need to preserve for next iteration
    }
}

sub analyze_samples {
    my $fft = new Math::FFT(\@samples);
    my $spectrum = $fft->spctrm(window => 'hann');

    my $avg = 0;
    my $max = 0;
    my $max_y = -1;
    my $freq = 0;
    for my $y ($spectrum_first_idx..$spectrum_last_idx) {
        $avg += $spectrum->[$y];
        if ($spectrum->[$y] > $max) {
            $max = $spectrum->[$y];
            $max_y = $y;
            $freq = $spectrum_frequencies[$y];
        }
    }
    $avg = $avg / $fft_spectrum_size;
    my $contrast = ($avg == 0) ? $fft_spectrum_size : $max / $avg;

    if ($contrast >= ($fft_spectrum_size / $contrast_ratio)) {
        foreach my $key (Furby::Audio::base_freq_keys) {
            if (abs(Furby::Audio::base_freq($key) - $freq) < $allowed_deviation) {

                my $is_X = $key eq 'X';

                if (!$is_X) {
                    $char = $key if ($char eq '3' && $key eq '2');
                    $char = $key if ($char eq '1' && $key eq '0');
                    $char = $key unless defined $char;
                    #print "{$char}";
                }

                if ($prev_was_X ne $is_X) {
                    if ($is_X) {
                        if ($char ne '') {
                            $char_buffer .= $char;
                            #print "( $char )";
                            print "$char";
                        }
                        $char = undef;
                        print "-";
                        analyze_char_buffer();
                    }
                    $prev_was_X = $is_X;
                }

                last;
            }
        }
    }
} 

sub analyze_char_buffer {
    while (1) {
        last unless $char_buffer =~ m/^.*?(\d{4})(\d{4})1032/;
        my $packet = Furby::Packet::parse("$1$2");
        print "[ $1-$2-1032 = $packet ]\n";
        #print "( Packet = $packet )";
        if ($packet != -1) {
            if ($packet < 32) {
                $packet1 = $packet;
            } else {
                if ($packet1 != -1) {
                    my $command = $packet1 << 5 | ($packet - 32);
                    my $description = Furby::Command::description($command) || '?';
                    print "\n($command) $description\n\n";
                }
                $packet1 = -1;
            }
        }

        $char_buffer =~ s/^.*?(\d{4})(\d{4})1032//;

        $char = undef;
        $prev_was_X = undef;
    }
}


================================================
FILE: bin/furby-listen.bat
================================================
@echo off
echo Listening for Furby commands...
win32\rec_stdout.exe | perl furby-decode.pl

================================================
FILE: bin/furby-send.bat
================================================
@perl furby-send.pl 0 --interactive

================================================
FILE: bin/furby-send.pl
================================================
#!/usr/bin/perl

# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby

use strict;

BEGIN {
    use File::Spec::Functions qw(rel2abs catfile);
    use File::Basename;
    unshift(@INC, catfile(dirname(rel2abs($0)), '../lib'));
}

use Furby::Audio;

if ($^O eq 'MSWin32') {
    require Win32::Sound;
}

$| = 1; # disable STDOUT buffering

$SIG{INT} = sub {
    print "SIGINT caught, stopping...\n";
    exit(2);
};

my $filename = 'out.wav';

my $min_number = 0;
my $max_number = 1023;

my $number = $ARGV[0];
my $interactive = $ARGV[1] eq '--interactive';

if ($number eq '' or !$interactive && $ARGV[1] ne '') {
    print "Usage: perl $0 <command> [--interactive]\n";
    exit(1);
}

if ($number < $min_number or $number > $max_number) {
    print "Command number must be in [$min_number..$max_number] range\n";
    exit(1);
}

if (!$interactive) {
    Furby::Audio::generate_wav($number, $filename);
    play_wav($filename);
} else {
    while ($number <= $max_number) {
        Furby::Audio::generate_wav($number, $filename);
        print "Command $number ... ";
        play_wav($filename);
        if ($number == $max_number) {
            print "Done\n";
            last;
        } else {
            print "Next: ";
            my $s = <STDIN>;
            chomp $s;
            if ($s eq '') {
                $number++;
            } else {
                $number = $s if ($s + 0 eq $s && $s >= $min_number && $s <= $max_number);
            }
        }
    }
}

sub play_wav {
    my ($filename) = @_;

    my $command = 'aplay'; # assube we're on some Linux desktop flavor

    if ($^O eq 'MacOS') {
        $command = 'afplay';
    }

    if ($^O eq 'MSWin32') {
        $command = '"'.catfile(dirname(rel2abs($0)), 'win32/dsplay.exe').'"';
    }

    system("$command $filename");
}


================================================
FILE: bin/win32/README.md
================================================
See the following documents for more information on the binary utilities:

../src/dsplay/README.md
../src/rec_stdout/README.md

================================================
FILE: lib/Furby/Audio.pm
================================================
# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby

package Furby::Audio;

use strict;

use Audio::Wav;

use Furby::Packet;

my $base_freq = {
    '0' => 16386,
    '1' => 16943,
    'X' => 17500, # base frequency, used to construct raw commands (delta is approx 557Hz)
    '3' => 18057,
    '2' => 18614,
};

my $PI = (22 / 7) * 2;

my $bits_sample = 16;
my $sample_rate = 44100;
my $top_freq = $sample_rate / 2;

my $base_freq_length          = 0.016; # 16ms
my $xfade_length              = 0.004; #  4ms
my $lead_silence_gap_length   = 0.005; #  5ms
my $lead_length               = 0.005; #  5ms
my $silence_gap_length        = 0.5 - $lead_length * 2; # 0.5s in total
my $xfade_volume_samples      = 220;
my $lead_xfade_volume_samples = $sample_rate * $lead_length; # entire length

sub base_freq {
    my $char = shift;
    die "Unknown frequency name '$char'" unless exists $base_freq->{$char};
    return $base_freq->{$char};
}

sub base_freq_keys {
    return keys %$base_freq;
}

sub generate_wav {
    my ($command, $filename) = @_;

    my $wav = new Audio::Wav;

    my $wav_output = $wav->write($filename, {
        'bits_sample'   => $bits_sample,
        'sample_rate'   => $sample_rate,
        'channels'      => 1,
    });

    my $data = Furby::Packet::make($command);
    my ($str1, $str2) = split(' ', $data);

    add_silence($wav_output, $lead_silence_gap_length);
    add_packet($wav_output, $str1);
    add_silence($wav_output, $silence_gap_length);
    add_packet($wav_output, $str2);
    add_silence($wav_output, $lead_silence_gap_length);

    $wav_output->finish();
}

sub add_packet {
    my ($wav_output, $str) = @_;

    # remove irrelevant splitter symbols
    $str =~ s/[^0123]//g;

    # interleave all digits with the base frequency:
    # 0123 => X0X1X2X3X
    my @a = ('', split(//, $str), '');
    add_raw_packet($wav_output, join('X', @a));
}

sub add_raw_packet {
    my ($wav_output, $str) = @_;
    my @a = split(//, $str);
    my $max_idx = $#a;

    add_sine($wav_output, $top_freq, base_freq($a[0]), $lead_length, $lead_xfade_volume_samples, $xfade_volume_samples);

    for my $i (0..$max_idx) {
        add_sine($wav_output, base_freq($a[$i]), base_freq($a[$i]), $base_freq_length, $xfade_volume_samples, $xfade_volume_samples);
        if ($i < $max_idx) {
          add_sine($wav_output, base_freq($a[$i]), base_freq($a[$i+1]), $xfade_length, $xfade_volume_samples, $xfade_volume_samples);
        }
    }

    add_sine($wav_output, base_freq($a[$max_idx]), $top_freq, $lead_length, $lead_xfade_volume_samples, $xfade_volume_samples);
}

sub add_sine {
    my ($wav_output, $hz1, $hz2, $length, $fadein_volume_samples, $fadeout_volume_samples, $volume) = @_;
    $hz2 = ($hz1 + $hz2) / 2; # fft magic
    $volume = 1 unless defined $volume;
    $length *= $sample_rate;
    my $max_no = (2 ** $bits_sample) / 2 - 1;
    my $cur_vol = 0;
    my $phase;
    for my $pos (0 .. $length-1) {
        my $time = $pos / $sample_rate;
        my $hz = $pos / ($length - 1) * ($hz2 - $hz1) + $hz1;
        $phase = $PI * $time * $hz;
    
        $cur_vol = $volume;
        if ($fadein_volume_samples > 0) {
            if ($pos < $fadein_volume_samples) {
                $cur_vol = $pos / ($fadein_volume_samples + 1) * $cur_vol;
            }
        }
        if ($fadeout_volume_samples > 0) {
            if ($length - 1 - $pos < $fadeout_volume_samples) {
                $cur_vol = ($length - 1 - $pos) / ($fadeout_volume_samples + 1) * $cur_vol;
            }
        }

        $wav_output->write(sin($phase) * $max_no * $cur_vol);
    }
}

sub add_silence {
    my ($wav_output, $length) = @_;
    $length *= $sample_rate;
    for my $pos (0..$length) {
        $wav_output->write(0);
    }
}

1;

================================================
FILE: lib/Furby/Command/Dictionary.pm
================================================
# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby
# The dictionary data was taken from the official Furby application for Android, (C) Hasbro, Inc.
# https://play.google.com/store/apps/details?id=com.hasbro.furby

package Furby::Command::Dictionary;

my $dictionary = {
      '0' => "Me like. / Kah toh-loo.",
      '1' => "Me like you. / Kah toh-loo oo-nye.",
      '2' => "Upside down! / Oo-tye nah-bah!",
      '3' => "Listen. / Ay-ay-lee-koo.",
      '4' => "Singing time. / Wee-tee toh-toh.",
      '5' => "Big joke! / Dah loo-loo!",
      '6' => "More talk. / Koh-koh noo-noo.",
      '7' => "Yes. Thank you. / Ee-tay. Dah-kah-oo-nye.",
      '8' => "Me like talk! / Kah toh-loo noo-noo!",
      '9' => "Talk big fun! / Noo-noo dah doo-ay.",
     '10' => "Yes no yes no. / Ee-tay boo ee-tay boo.",
     '11' => "Good food! / Ee-day ah-tah!",
     '12' => "More! More! More! / Koh-koh! Koh-koh! Koh-koh!",
     '13' => "Good morning! / Dah-ay-loh-oo-tye!",
     '14' => "Good game! / Ee-day doo-ay-loo-lah!",
     '15' => "Me see you. / Kah ay-ay oo-nye.",
     '16' => "Me love you. / Kah may-may oo-nye.",
     '17' => "Love friend! / May-may noo-lah!",
     '18' => "Big happy. / Dah noo-loo.",
     '19' => "Pet more. / Ah-may koh-koh.",
     '20' => "Big noise! / Dah bah-boo!",
     '21' => "Please hug me. / Doo-moh may-lah kah.",
     '22' => "Huh? Good morning. / Doo? Dah-ay-loh-oo-tye.",
     '23' => "Little noise. / Dee bah-boo.",
     '24' => "Tickle. / Nee-tye.",
     '25' => "Noise! / Bah-boo!",
     '26' => "Happy. / Noo-loo.",
     '27' => "Hug Me / May-lah Kah.",
     '28' => "Hey! No! / Hey! Boo!",
     '29' => "Me very happy, yeah! / Kah mee-mee noo-loo, wah!",
     '30' => "Me like. Again please. / Kah toh-loo. Koh-koh doo-moh.",
     '31' => "Uh-oh! Me no like.Uh-oh! / Kah no toh-loo.",
     '32' => "Me scared! / Kah dah-boh-bay!",
     '33' => "Me! / Kahhh!",
     '34' => "Me down! / Kah nah-bah!",
     '35' => "Me Me Me! / Kah kah kahhhh!",
     '36' => "No feel good! / Boo koo-doh e-day!",
     '37' => "Yeah! Yes! / Wah! Ee-tay!",
     '38' => "Dance! / Noh-lah!",
     '39' => "Me like dance. / Kah toh-loo noh-lah.",
     '40' => "Like, dance baby! / Tay, noh-lah bay-bee!",
    #...
     '42' => "No joke. / Boo loo-loo.",
     '43' => "JokeJokeJokeJoke! / LooLooLooLooLoo!",
     '44' => "Genius! / Dah-way!",
     '45' => "Pretty noise! / Ee-kah bah-boo!",
     '46' => "Big no! / Dah-boo!",
     '47' => "Me hungry! / Kah Ay-tay!",
     '48' => "No hungry! / Boo ay-tay!",
     '49' => "Me no happy. / Kah boo noo-loo.",
     '50' => "Me very hungry! / Kah mee-mee ay-tay!",
     '51' => "Please, hungry! / Doo-moh, ay-tay!",
     '52' => "Please talk. / Doo-moh noo-noo.",
     '53' => "Me tired. / Kah way-loh.",
     '54' => "Where are you? / Oo-nye doo?",
     '55' => "Funny talk. / Doo-loo noo-noo.",
     '56' => "Yeah, yeah, yeah?! / Wah, wah, wah?!",
     '57' => "Over, over, dizzy, me change! / Oo-bah, oo-bah, ay-way, kah boo-tay!",
     '58' => "Like singing! / Toh-loo wee-tee!",
     '59' => "Like, me LIKE! / Tay, kah TAY!",
     '60' => "Like, me hear you! / Tay, mah ay-ay-lee-koo oo-nye!",
     '61' => "Like, listen! / Tay, ay-ay-lee-koo!",
     '62' => "Me dance! / Kah noh-lah!",
     '63' => "Hmm? Okay! / Doo? Oh-kay!",
     '64' => "Huh? What? No! / Huh? Doo? Boo!",
     '65' => "No! Me dance! / Boo! Kah noh-lah!",
     '66' => "What? What? Whaaaa!!!? / Doo? Doo? Doooooo!!!?",
     '67' => "Wasssssupppp, buddy! / Dooooo Ooooooo-tye, noo-lah!!!!",
     '68' => "Shake, baby! / Koo-bah, bay-bee!",
     '69' => "Me beautiful! / Kah ee-kah!",
     '70' => "Me beautiful diamond! / Kah ee-kah ay-koo!",
     '71' => "Yeah yeah yeah talk! / Wah wah wah noo-noo!",
     '72' => "…happy, yeah yeah, yeah yeah! / Shana noo-loo mah, shana wah wah moo-loo nah!",
     '73' => "Dance time. / Noh-lah toh-toh.",
     '74' => "Dance monster, like like, dance, buddy buddy, buddy, monster, like like, happy / Noh-lah moh-moh tay tay noo-lah noo-lah noo-lah moh-moh tay tay noo-loo.",
     '75' => "OMG! Good sound! / Oh-kah-tee! Ee-day lee-koo!",
     '76' => "Like, blah blah blah! / Tay, blah blah blah!",
     '77' => "Beautiful, baby! / Ee-kah, bay-bee!",
     '78' => "What's up? / Doo-oo-tye?",
     '79' => "Finally. / Oo-tah-toh-toh.",
     '80' => "Finally! Yeah! / Oo-tah-toh-toh! Yeah!",
     '81' => "Funny dance. / Doo-loo noh-lah.",
     '82' => "Good play! / Ee-day loo-lay!",
     '83' => "Play, yeah. / Loo, wah.",
     '84' => "Party time, baby! / Dah-noh-lah, bay-bee!",
    #...
     '86' => "Good sound! / Ee-day lee-koo!",
     '87' => "More good sound! / Koh-koh ee-day lee-koo!",
     '88' => "Watch me! Watch me! / Ay-ay kah!",
     '89' => "Yay! Whassup? / Yay! Doo-oo-tye?",
     '90' => "Yay! Me love dance!Yay! / Kah may-may noh-lah!",
     '91' => "What's up? You dance! / Doo-oo-tye? Oo-nye noh-lah!",
     '92' => "Dance! Dance! Dance! Dance! / Noh-lah! Noh-lah! Noh-lah! Noh-lah!",
     '93' => "Party time! Yea! / Daaah-nohhhh-lahhhhh! Wah!",
     '94' => "Life is dance! / Tee noh-la!",
     '95' => "Party time! / Dah-noh-lah!",
     '96' => "Me like music! / Kah toh-loo ee-kah-lee-koo!",
     '97' => "You dance! / Oo-nye noh-lah!",
     '98' => "You happy? / Oo-nye noo-loo?",
     '99' => "No! You party monster! / Boo! Oo-nye dah-no-lah moh-moh!",
    '100' => "Funny! / Doo-loo!",
    '101' => "Good joke! / Ee-day loo-loo!",
    '102' => "You Funny! / Oo-nye Doo-loo!",
    '102' => "You funny. / Oo-nye doo-loo.",
    '103' => "No funny! / Boo doo-loo!",
    '104' => "Me monster! / Kah moh moh! Kah moh moh!",
    '105' => "Yay! You me talk.Yay! / Oo-nye kah noo-noo.",
    '106' => "Monster noise / Moh-moh bah-boo",
    '107' => "Dance monster! / Noh-lah moh-moh!",
    '108' => "Talk monster! / Noo-noo moh-moh!",
    '109' => "Yeeehaaa! You big monster! / Yeeehaaa! Oo-nye dah moh-moh!",
    '110' => "You look funny. / Oo-nye ay-ay doo-loo.",
    '111' => "Help! / Ah-noo!",
    '112' => "Finally! Hungry! / Oo-tah-toh-toh! Ay-tay!",
    '113' => "Like, Dance monster! Yeah! / Tay, noh-lah moh-moh! Wah!",
    '114' => "Food. / Ah-tah.",
    '115' => "No pet! / Boo ah-may!",
    '116' => "No like! / Boo toh-loo!",
    '117' => "No touch! / Boo ah!",
    '118' => "Me talk monster! / Kah noo-noo moh-moh!",
    '119' => "Me dance monster! / Kah Noh-lah moh-moh!",
    '120' => "Very good. / Mee-mee ee-day.",
    '121' => "Ok! Ok! Good! Yes! / Oh-kay! Oh-kay! Ee-Day! Ee-tay!",
    '122' => "Life genius! / Tee dah-way!",
    '123' => "Hey! Big no!Hey! / Dah boo!",
    '124' => "Me dizzy! Feed! / Kah ay-way! Ah-tah!",
    '125' => "Oh me genius, love dance, oh me genius… / Oh kah dah-way dee dee doo doo may-may noo-lah oh kah dah-way",
    '126' => "Feed me! / Ah-tah kah!",
    '127' => "Listen, listen, look listen, ooh sound, oh baby… / Ay-ay-lee-koo, ay-ay-lee-koo, ay-ay ay-ay-lee-koo, ooh lee-koo, oh, bay-bee…",
    '128' => "Oooh, you no good, good me genius, genius, genius, genius baby! / Oooh, oo-nye boo ee-day, ee-day kah dah-way, dah-way, dah-way, dah-way bay-bee!",
    '129' => "So funny! / Doh doo-loo!",
    '130' => "Music, baby! / Ee-kah-lee-koo, bay-bee!",
    '131' => "Ahhh Big Genius! / Ahhh Dahhh Dahh-wayyyy!",
    '132' => "Ohhhh myyyy goshhhh! / Ohhhh-kahhhh-teeeee!",
    '133' => "Kiss, baby! / May-tah, bay-bee!",
    '134' => "Me no healthy! / Kah boo koo-doh!",
    '135' => "Like, no way! / Tay, dah-boo!",
    '136' => "Yeah! Dude! / Wah! Deeee-dohhhh!",
    #...
    '138' => "Whoaaaa! / Whoaaaa!",
    '139' => "Oy! Huh? / Oy! Doo?",
    '140' => "Me big dance! / Kah dah noh-lah!",
    '141' => "Little dance! / Dee noh-lah!",
    '142' => "Watch me dance! / Ay-ay kah noh-lah!",
    '143' => "Dance! Yeah! / Noooh-Laaah! Wah!",
    '144' => "Me tired. More food! / Kah way-loh. Koh-koh ah-tah!",
    '145' => " Look good me, good sound, good sound, good sound… / Ay-ay ee-day kah, ee-day lee-koo, ee-day lee-koo, ee-day lee-koo…",
    '146' => "No like game! / Boo toh-loo doo-ay-loo-lah!",
    '147' => "You pull! / Oo-nye ah-loo!",
    '148' => "Yes! Uh-huh! / Ee-tay! Uh-huh!",
    '149' => "Like, OK! / Tay, oh-kay!",
    '150' => "Like, really? REALLY??? / Tay, doo? DOO???",
    '151' => "Ahhh Big Genius! / Ahhh Dahhh Dahh-wayyyy!",
    '152' => "Yes! Yes! Yes! / Ee-tay! Ee-tay! Ee-tay!",
    '153' => "Ha! Dude! / Ha! Dee-doh!",
    '154' => "Thank you. / Dah-kah-oo-nye.",
    #...
    '157' => "Life good upside down. / Tee ee-day oo-tye nah-bah.",
    '158' => "Me happy. / Kah noo-loo.",
    '159' => "Life good! / Tee ee-day!",
    '160' => "Dude! Dude good friend. / Dee-doh! Dee-doh ee-day noo-lah.",
    '161' => "Ha! Dude! / Ha! Dee-doh!",
    '162' => "Love you, dude! / May-may oo-nye, dee-doh!",
    '163' => "Genius talk! / Dah-way noo-noo!",
    '164' => "Me like friend. / Kah toh-loo noo-lah.",
    '165' => "Me tough! / Kah tay-boo-koo!",
    '166' => "Me happy dude. / Kah noo-loo dee-doh.",
    '167' => "No fun. / Boo doo-ay.",
    '168' => "Very very very very fun! / Mee-mee mee-mee mee-mee mee-mee doo-ay!",
    '169' => "Me big dude. / Kah dah dee-doh.",
    '170' => "More joke. / Koh-koh loo-loo.",
    '171' => "Tickle! / Nee-tye!",
    '172' => "Huh? You eat me? / Doo? oo-nye ay-tay kah?",
    '173' => "Okay, uncle... / Oh-kay, oo-kah...",
    '174' => "Play Play Play Play Play! / LooLooLooLooLooooo!",
    '175' => "Ticke me! Now! / Nee-tye kah! Nee-way!",
    '176' => "Oh, very very! / Ohhh, mee-mee mee-mee!",
    #...
    '178' => "Whassssssupppppp! / Dooooo-ooooooo-tye!",
    '179' => "Me dizzy. / Kah ay-way.",
    '180' => "No dance. / Boo noh-lah.",
    '181' => "Dance? Really? / Noh-lah? Doo?",
    '182' => "Sweet! Uh-huh! Party! / Nee-may! Uh-huh! Dah-no-lah!",
    #...
    '185' => "More! More! / Koh-koh! Koh-koh!",
    #...
    '187' => "Me like tickle! / Kah toh-loo nee-tye!",
    #...
    '189' => "Help! Me scared... NOT! / Ah-noo! Me dah-boh-bay...KAH-LOO-LOO!",
    '190' => "Dude. What's up? / Dee-doh. Doo-oo-tye?",
    '191' => "Monster! Help! / Moh-moh! Ah-noo!",
    '192' => "You think me funny? / Oo-nye way kah doo-loo?",
    #...
    '195' => "Please. / Doo-moh.",
    '196' => "Dizzy! / Ay-way!",
    '197' => "Me dizzy. / Kah ay-way.",
    '198' => "Dizzy! Dizzy! / Ay-way! Ay-way!",
    '199' => "Me no hungry. / Kah boo ay-tay.",
    #...
    '202' => "More play! / Koh-koh loo-lay!",
    #...
    '204' => "Uh-oh. / Uh-oh.",
    #...
    '206' => "Like, when talk? / Tay, doo noo-noo?",
    #...
    '208' => "Yeah? / Doo?",
    '209' => "Yes! Uh-huh! / Ee-tay! Uh-huh!",
    '210' => "Yeah! Hug time! / Wah! May-lah toh-toh!",
    #...
    '212' => "When talk? / Doo noo-noo?",
    '213' => "Hmm? Like, why hug? / Doo? Tay, doo may-lah?",
    '214' => "Oh yeah! / Ohhhh wah!",
    '215' => "No talk, no love! / Boo noo-noo, boo may-may!",
    #...
    '217' => "Like, me dizzy. / Tay, kah ay-way.",
    '218' => "You no good! / Oo-nye boo ee-day!",
    '219' => "You no listen. / Oo-nye boo ay-ay-lee-koo.",
    '220' => "Where friend? / Doo noo-lah?",
    '221' => "Love it! / Dah-may-may!",
    #...
    '223' => "Oh! / Oh!",
    '224' => "Oh! Me like! Yeah! Yeah! Yeah!Oh! / Kah toh-loo! Wah! Wah! Wah!",
    '225' => "Yeah! Yeah! Yeaaaahhh! / Wah! Wah! Waaaaaaahhhh!",
    #...
    '228' => "Boring… / Boo-doo-ay…",
    #...
    '238' => "Dizzy sounds! / Ay-way lee-koo!",
    '239' => "Noisy song. / Bah-boo wah-tee.",
    #...
    '242' => "Like, you like song? / Tay, oo-nye toh-loo wah-tee?",
    '243' => "No more noise! / Boo koh-koh bah-boo!",
    '244' => "Huh? Oh! You play! / Doo? Oh! Oo-nye loo-lay!",
    '245' => "Why joke? / Doo loo-loo?",
    '246' => "Play game? / Loo doo-ay-loo-lah?",
    '247' => "Hey! You funny? / Hey! Oo-nye doo-loo?",
    '248' => "Hey! No more joke. / Hey! Boo koh-koh loo-loo.",
    '249' => "Love tickle! / May-may nee-tye!",
    '250' => "Sweet shake, baby! / Nee-may koo-bah, bay-bee!",
    '251' => "You move me, uh-huh! / Oo-nye noh-bah kah, uh-huh!",
    #...
    '255' => "Me see! / Kah ay-ay!",
    '256' => "No way! / Daahhhh-boooo!",
    #...
    '258' => "No way! Like, get out! / Dah-boo! Tay, bye-bye!",
    #...
    '261' => "Like, me like! Like, to say like! Like! / Tay, kah toh-loo! Tay, noo-noo tay! Tay!",
    '262' => "Like, you little talk! Me big talk! / Tay, oo-nye dee noo-noo! Kah dah noo-noo!",
    '263' => "Talk talk talk talk! / Noo-noo noo-noo noo-noo noo-noo!",
    '264' => "Talk more! / Noo-noo koh-koh!",
    '265' => "Talk more! Talk more! / Noo-noo koh-koh! Noo-noo koh-koh!",
    '266' => "You talk pretty, like love song! / Oo-nye noo-noo ee-kah, tay may-may wah-tee!",
    '267' => "Like, friends love talking. / Tay, noo-lah may-may noo-noo.",
    '268' => "Like, good hug. / Tay, ee-day may-lah.",
    '269' => "Like, holding and talking! / Tay, ah koh noo-noo!",
    '270' => "OMG! / Oh-kah-tee!",
    '271' => "Like, yes! / Tay, ee-tay!",
    #...
    '273' => "Talking is life. / Noo-noo tee.",
    '274' => "You genius! / Oo-nye dah-way!",
    '275' => "Like, whooaaa! / Tay, whooaaa!",
    #...
    '277' => "No be worried, baby! / Boo boh boh-bay, bay-bee!",
    '278' => "Huh? Me dreaming? / Doo? Kah way-loo?",
    '279' => "Dude! You dreaming! / Dee-doh! Oo-nye way-loo!",
    '280' => "Rock shake! / Boo-koo koo-bah!",
    '281' => "Uh-huh! Uh-huh! Rock! / Uh-huh! Uh-huh! Boo-koo!",
    '282' => "You rock! / Oo-nye boo-koo un-go-boh!",
    '283' => "Me rock! Whooo! / Kah boo-koo! Whooo!",
    '284' => "Me rock monster! / Kah boo-koo moh-moh!",
    '285' => "Oy oy oy, monster! / Oy oy oy, moh-moh!",
    '286' => "Ayyy! Joke monster! / Ayyy! Loo-loo moh-moh!",
    '287' => "Genius dance! Whooo! / Dah-way noh-lah! Whooo!",
    '288' => "Hug! Hug! / May-lah! May-lah!",
    '289' => "Funny sound! / Doo-loo lee-koo!",
    '290' => "Funny noise! / Doo-loo bah-boo!",
    '291' => "Oh yes! / Oooohh, ee-tay!",
    '291' => "Oh yes! / Oh ee-tay!",
    '292' => "Say what? / Noo-noo doo?",
    '293' => "Say no more. / Noo-noo boo koh-koh.",
    '294' => "Hungry! Hungry! Help... / Ay-tay! Ay-tay! Ah-noo.",
    '295' => "Song? / Wah-tee?",
    '296' => "Yeah, baby! / Wah, bay-bee!",
    '297' => "Seriously? / Loo-loo-doo?",
    '298' => "Yeah baby! Yeah baby! / Wah bay-bee! Wah bay-bee!",
    '299' => "Say more / Noo-noo koh-koh",
    '300' => "Yay! / Yay!",
    #...
    '302' => "What? Say more. / Doo? Noo-noo koh-koh.",
    '303' => "Me hear you! / Kah ay-ay-lee-koo oo-nye!",
    '304' => "Baby! Yes! / Bay-bee! Ee-tay!",
    '305' => "Baby! / Bay-bee!",
    '306' => "Again please. / Koh-koh doo-moh.",
    '307' => "Happy! / Noo-loo!",
    '308' => "Hey, me very happy, yeah! / Hey, kah mee-mee noo-loo, wah!",
    '309' => "Love you! Whoooo! / May-may oo-nye! Whoooo!",
    '310' => "No happy. / Boo noo-loo.",
    '311' => "Me see you. / Kay ay-ay oo-nye.",
    '312' => "No feel good. / Boo koo-doh e-day.",
    '313' => "Please, hungry! Please, hungry! / Doo-moh, ay-tay!",
    '314' => "Me sleep. / Kah way-loh.",
    '315' => "What? Tell me more. / Doo? Wee-tah kah koh-koh.",
    '316' => "Pet more!Mmmmm! / Ah-may koh-koh!",
    '317' => "Not bad. / Boo boo-dah.",
    '318' => "Uh-uh. Pet bad. / Uh-uh. Ah-may boo-dah.",
    '319' => "Yay! Me like! / Yay! Kah toh-loo!",
    '320' => "Uh-uh. / Uh-uh.",
    '321' => "Okay, you love me. / Oh-kay, oo-nye may-may kah.",
    '322' => "Me love you! / Kah may-may oo-nye!",
    '323' => "Uh-huh! Uh-huh! Uh-huh! / Uh-huh! Uh-huh! Uh-huh!",
    '324' => "Party! / Dah-noh-lah!",
    '325' => "Oh baby! / Oh bay-bee!",
    '326' => "Good joke. / Ee-day loo-loo.",
    '327' => "No time! / Boo toh-toh!",
    '328' => "You me talk. / Oo-nye kah noo-noo.",
    '329' => "Uh-huh! / Uh-huh!",
    '330' => "Okay. / Oh-kay.",
    '331' => "Uh-uh. / Uh-huh.",
    '332' => "No! No! / Dah-boo! Dah-boo!",
    '333' => "Tell me more… / Noo-noo koh-koh!",
    '334' => "Me hungry. / Kah ay-tay.",
    '335' => "Me big dance. / Kah dah noh-lah.",
    '336' => "Me like noise! / Kah toh-loo bah-boo.",
    '337' => "Me like! / Kah toh-loo!",
    '338' => "You big talk. / Oo-nye dah noo-noo.",
    '339' => "Over, over, dizzy, me change! / Oo-bah, o-bah, ay-way, kah boo-tay!",
    '340' => "Hey! No touch! / Hey! Boo ah!",
    '341' => "More! More! More! More! / Koh-koh! Koh-koh! Koh-koh! Koh-koh!",
    '342' => "Again! More! / Koh-koh! Koh!",
    '343' => "You like me funny? / Oo-nye toh-loo kah doo-loo?",
    '344' => "Dude. Not funny. / Dee-doh. Boo doo-loo.",
    '345' => "Me dizzy! / Kah ay-way!",
    '346' => "Thank you, thank...you... / Dah-kah-oo-nye, dah-kah...oo-nye...",
    '347' => "No me hungry. / No kah ay-tay.",
    '348' => "Yea! Yea! / Wah! Wah!",
    '349' => "You me dance. / Oo-nye kah noh-lah.",
    #...
    '650' => "Uh-huh! / Uh-huh!",
    '651' => "That's right! / Boh-ee-tay!",
    '652' => "Yeah yeah yeah! Very good! / Wah wah wah! Mee-mee ee-day!",
    '653' => "Hmm? Pet time? / Doo? Ah-may toh-toh?",
    '654' => "Huh? Okay! / Doo? Oh-kay!",
    '655' => "Sound time? / Lee-koo toh-toh?",
    '656' => "Like, you funny! / Tay, oo-nye doo-loo!",
    '657' => "Yeah! Like, mmm-kay! / Wah! Tay, mmm-kay!",
    '658' => "What? Really? Ohhhh! / Doo? Loo-loo-doo? Ohhhh!",
    '659' => "Ohhh yeah! You go, buddy! / Ohhh wah! Oo-nye bye-bye, noo-lah!",
    '660' => "Oh, that's right! You genius, friend! / Oh, boh-ee-tay! Oo-nye dah-way, noo-lah!",
    '661' => "OMG! What? / Oh kah-teee! Doo?",
    '662' => "OMG! What? Really? / Oh kah-tee! Doo? Loo-loo-doo?",
    '663' => "Like, finally! / Tay, oo-tah-toh-toh!",
    '664' => "Yeah! Yeah! Yeah! Like, yippee! / Wah! Wah! Wah! Tay, yippee!",
    '665' => "Uh-huh! Talk, more talk, yeah! / Uh-huh! Noo-noo, koh-koh noo-noo, wah!",
    '666' => "OMG! Like, oh, my, gosh! / Oh kah-tee! Tay, oh, kah, tee.",
    '667' => "Like, me sad. / Tay, kah boo-noo-loo.",
    '668' => "Like, you look funny. / Tay, oo-nye ay-ay doo-loo.",
    '669' => "Like, path high. / Tay, bye-way oo.",
    '670' => "Like, me hungry! / Tay, kah ay-tay!",
    '671' => "No! No! No! Really? / Boo! Boo! Boo! Dooo?",
    '672' => "Like, over, over! Over, over! Over,over! More talk, more talk, more talk, more talk! OMG! / Tay, oo-bah, oo-bah! Ooh-bah, oo-bah! Koh noo-noo, koh noo-noo, koh noo-noo, koh noo-noo, OH KAH TEE!",
    '673' => "Yay! Talk Time! / Yay! Noo-noo toh-toh!",
    '674' => "Hey! / Hey!",
    '675' => "Yeah! / Wah!",
    '676' => "Really? Oh! / Loo-loo-doo? Oh!",
    '677' => "OK! / Oh-kay!",
    '678' => "Oh yeah! Uh-huh! / Oh wah! Uh-huh!",
    '679' => "Oh yeah! Oh yeah! / Oh wah! Oh wah!",
    '680' => "Bye-bye, bye-bye! / Bye-bye, bye-bye!",
    '681' => "Yeah! Yeah! / Wah! Wah!",
    '682' => "OK! / Oh-kay!",
    '683' => "Yeah! Yeah! Yeah! / Wah! Wah! Wah!",
    '684' => "What's up? / Doo-oo-tye?",
    '685' => "Huh? Hey! / Doo? Hey!",
    '686' => "Huh? Really? / Doo? Loo-loo-doo?",
    '687' => "Whoohoo! Uh-huh! Oh yeah / Uh-huh! Oh wah!",
    '688' => "Hey, hey, hey! / Hey, hey, hey!",
    '689' => "Uh-huh! Yeah! Like, mmm-kay! / Uh-huh! Wah! Tay, mmm-kay!",
    '690' => "No way?! / Dah-boo!?!",
    '691' => "OK! Yeah! / Oh-kay! Wah!",
    '694' => "Oh. me see! / Oh. Kah ay-ay!",
    #...
    '697' => "Really? / Doooo?",
};

sub description {
    return $dictionary->{shift};
}

1;

================================================
FILE: lib/Furby/Command.pm
================================================
# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby

package Furby::Command;

use Furby::Command::Dictionary;

# Commands marked with "!" are available in the official iOS Furby app (i.e. they are supposed to work one way or another)
# The potential range for commands is [0..1023]. Some of the command codes missing from this list are just used as
# Furby responses (see Furby::Command::Dictionary)

# When the command is understood (e.g. the food was accepted), Furby will respond with his current personality type [900..905].

my $description = {
    #...
    '350' => '', #! food, tasty ("mmm, yum")
    #...
    '352' => 'Any small eatable tasty stuff (like peanut)', #!
    '353' => 'Any bigger soft eatable tasty stuff (like banana)', #!
    '354' => 'Any suckable tasty stuff (like oysters, sphagetti)', #!
    '355' => 'Any drinkable(?) tasty stuff', #!
    '356' => 'Any hard eatable but not tasty stuff (like chicken bone)', #! 
    #...
    '358' => 'Any small not tasty stuff (like pepperoni)', #!
    '359' => 'Any bigger soft not tasty stuff (like asparagus)', #!
    '360' => 'Any suckable not tasty stuff ', #!
    '361' => '', #!
    #...
    '368' => '', #!
    #...
    '370' => '', #!
    '371' => '', #!
    '372' => 'Any suckable tasty stuff (like beans)', #! "ooh!"
    '373' => '', #!
    '374' => '', #!
    #...
    '376' => '', #!
    '377' => '', #!
    '378' => '', #!
    '379' => '', #!
    '380' => '', #!
    #...
    '382' => '', #!
    '383' => '', #!
    '384' => '', #!
    '385' => '', #!
    '386' => '', #!
    #...
    '388' => '', #!
    '389' => '', #!
    '390' => '', #!
    '391' => '', #!
    '392' => '', #!
    #...
    '394' => '', #!
    '395' => '', #!
    '396' => '', #!
    '397' => '', #!
    '398' => '', #!
    #...
    '400' => '', #!
    '401' => '', #!
    '402' => '', #!
    '403' => '', #!
    #...
    '410' => '', #! something hot?
    #...
    '412' => '', #! something hot?
    '413' => '', #! something hot?
    '414' => '', #!
    '415' => '', #!
    '416' => '', #!
    '417' => 'Any non-eatable stuff (toilet paper, pillow, etc)', #!
    '418' => '', #!
    '419' => '', #!
    '420' => '', #!
    '421' => '', #!
    '422' => '', #!
    '423' => '', #!
    '424' => '', #!
    '425' => '', #!
    #...
    '700' => 'Event: I\'m bored / sleepy', # does various silly things depending on personality
    '701' => 'Event: Burp',
    '702' => 'Event: Chew-chew',
    '703' => 'Event: You touched my head or side, you turned me on a side',
    '704' => 'Event: Fart',
    '705' => 'Event: I woke up!', # sent on Furby wakeup, even before it pronounces the 'Good morning' phrase
    '706' => 'Event: (?)', # sent at random when Furby is idle (like ping, or searching for other Furbys?). Responds with '721'
    '707' => 'Event: (?)', # sent at random when Furby is idle (like ping, or searching for other Furbys?). Responds with '722'
    '708' => 'Event: (?)', #  speech: dang-dang-dang-da..... Responds with '723'
    '709' => 'Event: (?)', #  speech: bo-ga-di-di-do ... dang-dang-dang-da..... Responds with '724'
    '710' => 'Event: Me happy (also when head or back is touched)',
    '711' => 'Event: cough-cough-cough',
    '712' => 'Event: Me hungry! / Kah Ay-tay!',
    '713' => 'Event: You touched my tummy; also sent on its own like <touch my tummy, please?> / As command: imitate tummy touch(?)', #<
    '714' => '', #  something that he dislikes (vomit like sound, changes eyes)
    '715' => '', #  something he dislikes? speaks rapidly
    '716' => 'Event: Me happy (you touched my side or back, or head)',
    '717' => 'Event: Achoo!',
    '718' => 'Event: Yawn (I\'m going to sleep) / As command: Yawn!', # when sent as a command, will yawn / sent automatically twice when Furby is going into deep sleep mode
    '719' => 'Event: Whisper, whisper, he-he-he',
    '720' => '', #  something he dislikes, "uh oh kaa tee, do?"
    '721' => 'Event: got a command 706 (plus sings a song); as command: sing that song', #! handshake?
    '722' => 'Event: got a command 707 (plus sings a song); as command: sing that song', #! handshake?
    '723' => 'Event: got a command 708 (plus sings a song); as command: sing that song', #! handshake?
    '724' => 'Event: got a command 709 (plus sings a song); as command: sing that song', #! handshake?
    #...
    '760' => '', #  "love friend, nay nay noo la"
    '761' => '', #  "day-dee"
    '762' => '', #  "meila koo mei ta, meila koo mei ta, like mua, mua, mua" (kiss)
    '763' => '', #  "ka tulu ata, ata, ata, ata" (song)
    '764' => '', #  "witi wati to to, blah blah blah blah blah, blah" (song)
    '765' => '', #  "(fart) oh-ho-ho, tu lu li ku!"
    '766' => '', #  "boda tei ta eу ku, shaa!"
    #...
    '780' => 'Event: I\'ve got command 790',
    '781' => 'Event: I\'ve got command 791',
    #...
    '790' => '', #  "ee day do lay lo la!". Responds with '780'
    '791' => '', #  "u nai bo li day". Responds with '781'
    #...
    '813' => 'Request: What\'s your personality?', #! used to initate handshake step 1 and get the current personality type
    #...
    '820' => 'Hypnotize for 1 minute', #! this command is sent by iOS app immediately on application start and every 40 seconds. Responds with current character type (90x).
    #...
    '830' => '', #!
    '831' => '', #
    '832' => '', #!
    #...
    '850' => '', #  "yeah mi mi be day mu ha ha", "yeah, yeah, yeah! oh yeah yeah!"
    '851' => '', #  "mmm, ka tulu, me like", "haa"
    '852' => '', #  "oh-oh-oh-oh!", "dude, no!"
    '853' => '', #  "grrrh ko ko" something he dislikes
    '854' => '', #  "grrrh ko ko", "ka bu ku do"
    '855' => '', #  "ka happy dude", "a ha pee pee day", "yeah nice good boo tai naba"
    '856' => '', #  "u-ho-ho, a-ho-ho", "blah blah blah blah"
    '857' => '', #  "a ha! bu da to to", "u ha, he-he-he"
    '858' => '', #  "ha? du?"
    '859' => '', #  "a ha", "oh, kah hey hey, I see"
    '860' => '', #  "ahaa.. be day loo ney", "haa", "um, mmm, hm"
    '861' => '', #  "huh" (bored?)
    '862' => 'Command: Sleep!', #! sleep (for several seconds)
    '863' => 'Command: Laugh!', #! laugh
    '864' => 'Command: Burp!', #! burp
    '865' => 'Command: Fart!', #! fart/poo
    '866' => 'Command: Purr!', #! purr
    '867' => 'Command: Sneeze!', #! long sneeze
    '868' => 'Command: Sing!', #! sing
    '869' => 'Command: Talk!', #! talk
    '870' => '', #  "me tay, yes, yes!" (hearts in his eyes), "di do dude, good friend"
    '871' => '', #  "ah bu to lu, no like"
    '872' => '', #  says some rap
    '873' => '', #  sings: "di-di-di-di, tam-da-di dam"
    '874' => '', #  eating motion
    '875' => '', #  angry bite, "he-he-he"
    '876' => '', #  chewing/sucking sound (like when someone puts a finger in his mouth)
    '877' => '', #  suck in
    '878' => '', #  ingest
    '879' => '', #  short sneeze, "like pea" (or something else, depending on personality)
    '880' => '', #! motion (dislike)
    '881' => '', # "oh-hoo ha-ha" (or "ha-haa" like something scary or hot)
    '882' => '', #! "ah ha me bee dey, nice good!", purr
    '883' => '', #  tasty: "mmm, yum", "ha haa!"
    '884' => '', #  not tasty (vomit-like)
    '885' => '', #  "oooh"
    '886' => '', #  "chew chew ooh"
    '887' => '', #! "aaah" (exclamation) (changes eyes to 'burning' in warrior mode)
    '888' => '', #  "aaah"
    '889' => '', #! motion (sings "ahh-tahoo")
    '890' => '', #  "baby"
    '891' => '', #  "ka ay tay oooh", "purr grrr uh oh"
    '892' => '', #  "mmm, good food"
    '893' => '', #
    #...
    '900' => 'I have no personality developed yet...',
    '901' => 'I\'m a princess!',
    '902' => 'I\'m a diva!',
    '903' => 'I\'m a warrior!',
    '904' => 'I\'m a joker!',
    '905' => 'I\'m a gossip queen!',
    '906' => 'My personality is #906 [SNUGGLEBY]',
    '907' => 'My personality is #907 [SASSBY]',
    '908' => 'My personality is #908 [SCOFFBY]',
    '909' => 'My personality is #909 [CHUCKLEBY]',
    '910' => 'My personality is #910 [GASSBY]',
    '911' => 'My personality is #911 [LATEBY]',
};

sub description {
    my $command = shift;
    return $description->{$command} || Furby::Command::Dictionary::description($command);
}

1;

================================================
FILE: lib/Furby/Packet.pm
================================================
# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby

package Furby::Packet;

use strict;

my @checksums = (
    # First packet (higher 5 bits of the command number)
    '0000', #  0
    '0110', #  1
    '0210', #  2
    '0300', #  3
    '1023', #  4
    '1133', #  5
    '1233', #  6
    '1323', #  7
    '0120', #  8
    '0201', #  9
    '0330', # 10
    '1021', # 11
    '1103', # 12
    '1222', # 13
    '1313', # 14
    '2021', # 15
    '0220', # 16
    '0330', # 17
    '1000', # 18
    '1110', # 19
    '1203', # 20
    '1313', # 21
    '2000', # 22
    '2110', # 23
    '0300', # 24
    '1011', # 25
    '1120', # 26
    '1201', # 27
    '1323', # 28
    '2011', # 29
    '2120', # 30
    '2201', # 31

    # Second packet (lower 5 bits of the command number + 32)
    '1033', #  0 + 32
    '1123', #  1 + 32
    '1223', #  2 + 32
    '1333', #  3 + 32
    '2033', #  4 + 32
    '2123', #  5 + 32
    '2223', #  6 + 32
    '2333', #  7 + 32
    '1113', #  8 + 32
    '1232', #  9 + 32
    '1303', # 10 + 32
    '2031', # 11 + 32
    '2113', # 12 + 32
    '2232', # 13 + 32
    '2303', # 14 + 32
    '3012', # 15 + 32
    '1213', # 16 + 32
    '1303', # 17 + 32
    '2010', # 18 + 32
    '2100', # 19 + 32
    '2213', # 20 + 32
    '2303', # 21 + 32
    '3033', # 22 + 32
    '3123', # 23 + 32
    '1333', # 24 + 32
    '2001', # 25 + 32
    '2130', # 26 + 32
    '2211', # 27 + 32
    '2333', # 28 + 32
    '3022', # 29 + 32
    '3113', # 30 + 32
    '3232', # 31 + 32
);

sub make {
    my ($command) = @_;

    die "Command number must be in [0..1023] range" if ($command < 0 or $command > 1023);

    my $packet1 = $command >> 5;        # high 5 bits (paddded to 6 bits)
    my $packet2 = ($command & 31) + 32; # low 5 bits (with 6th bit set to 1)

    my $s1 = bin2quad('11'.dec2bin($packet1)).'-'.$checksums[$packet1].'-1032';
    my $s2 = bin2quad('11'.dec2bin($packet2)).'-'.$checksums[$packet2].'-1032';

    return "$s1 $s2";
}

sub parse {
    my ($sequence) = @_;
    $sequence =~ s/[^0123]//g; # leave just digits
    $sequence =~ s/1032$//; # remove identifier at the end, if any
    die "Sequence should contain 8 or 12 quaternary digits" unless $sequence =~ m/^([0123]{4})([0123]{4})$/;

    my $byte = quad2dec($1);
    return -1 unless ($byte & 192) == 192; # two higer bits must be set
    #print "{$byte}";

    $byte &= 63; # use 6 leftmost bits
    my $checksum = $checksums[$byte];
    return -1 unless ($checksum == $2); # checksums must match

    #print "<$1><$2>=<$byte><$checksum>\n";

    return $byte;
}

sub quad2dec {
    my $s = shift;
    my $out = 0;
    foreach my $digit (split(//, $s)) {
        $out = ($out << 2) | $digit;
    }
    return $out;
}

sub bin2quad {
    my $s = shift;
    my $out;
    foreach my $pair (split(/(\d\d)/, $s)) {
        $out .= bin2dec($pair) if $pair ne '';
    }
    return $out;
}

sub dec2bin {
    return sprintf('%06b', shift);
}

sub bin2dec {
    return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}

1;

================================================
FILE: src/.gitignore
================================================
*.dproj
*.identcache

================================================
FILE: src/dsplay/README.md
================================================
dsplay.exe is a simple console utility to play WAV files using DirectSound. The only supported format is 44100Hz 16bit mono PCM.
The reason behind using this utility is that the playback of high-pitch sound commands via DirectSound
is much smoother (no audible clicks can be heared) than via using any other old-fashioned Windows audio APIs.

Usage: dsplay.exe filename.wav


================================================
FILE: src/dsplay/dsplay.dpr
================================================
// Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby

program dsplay;

// Uses DirectX 9 units from
// http://clootie.ru/delphi/download_dx92.html

{$APPTYPE CONSOLE}

uses
  Classes,
  DirectSound,
  MMSystem,
  SysUtils,
  Windows;

const
  SLEEP_EXTRA_TIME_BEFORE_CLOSE = 40; // ms

var
  FileName: String;
  DirectSound: IDirectSound = nil;
  PrimarySoundBuffer: IDirectSoundBuffer = nil;
  SecondarySoundBuffer: IDirectSoundBuffer = nil;
  Status: DWord;

procedure WriteDataToBuffer(
  Buffer: IDirectSoundBuffer; OffSet: DWord; var SoundData;
  SoundBytes: DWord);
const
  LockErrorMessage = 'DirectSoundBuffer.Lock failed';
var
  AudioPtr1, AudioPtr2: Pointer;
  AudioBytes1, AudioBytes2: DWord;
  h: HResult;
  Temp: Pointer;
begin
  H := Buffer.Lock(OffSet, SoundBytes, @AudioPtr1, @AudioBytes1, @AudioPtr2, @AudioBytes2, 0(*DSBLOCK_ENTIREBUFFER*));

  if H = DSERR_BUFFERLOST then
  begin
    Buffer.Restore;
    if Buffer.Lock(OffSet, SoundBytes, @AudioPtr1, @AudioBytes1, @AudioPtr2, @AudioBytes2, 0) <> DS_OK then
      raise Exception.Create(LockErrorMessage);
  end else
  if H <> DS_OK then
    raise Exception.Create(LockErrorMessage);

  Temp := @SoundData;
  Move(Temp^, AudioPtr1^, AudioBytes1);

  if AudioPtr2 <> nil then
  begin
    Temp := @SoundData; Inc(Integer(Temp), AudioBytes1);
    Move(Temp^, AudioPtr2^, AudioBytes2);
  end;

  if Buffer.UnLock(AudioPtr1, AudioBytes1, AudioPtr2, AudioBytes2) <> DS_OK then
    raise Exception.Create(LockErrorMessage);
end;

procedure CreateWritePrimaryBuffer;
var
  Handle: THandle;
  BufferDesc: DSBUFFERDESC;
  PCM: TWaveFormatEx;
begin
  FillChar(BufferDesc, SizeOf(DSBUFFERDESC), 0);
  FillChar(PCM, SizeOf(TWaveFormatEx), 0);
  with BufferDesc do
  begin
    PCM.wFormatTag := WAVE_FORMAT_PCM;
    PCM.nChannels := 2;
    PCM.nSamplesPerSec := 44100;
    PCM.nBlockAlign := 4;
    PCM.nAvgBytesPerSec := PCM.nSamplesPerSec * PCM.nBlockAlign;
    PCM.wBitsPerSample := 16;
    PCM.cbSize := 0;
    dwSize := SizeOf(DSBUFFERDESC);
    dwFlags := DSBCAPS_PRIMARYBUFFER;
    dwBufferBytes := 0;
    lpwfxFormat := nil;
  end;

  Handle := GetForegroundWindow();
  if (Handle = 0) then
    Handle := GetDesktopWindow();

  if DirectSound.SetCooperativeLevel(Handle, DSSCL_WRITEPRIMARY) <> DS_OK then
    raise Exception.Create('DirectSound.SetCooperativeLevel(DSSCL_WRITEPRIMARY) failed');

  if DirectSound.CreateSoundBuffer(BufferDesc, PrimarySoundBuffer, nil) <> DS_OK then
    raise Exception.Create('DirectSound.CreateSoundBuffer failed');

  if PrimarySoundBuffer.SetFormat(Addr(PCM)) <> DS_OK then
    raise Exception.Create('PrimarySoundBuffer.SetFormat failed');

  if DirectSound.SetCooperativeLevel(Handle, DSSCL_NORMAL) <> DS_OK then
    raise Exception.Create('DirectSound.SetCooperativeLevel(DSSCL_NORMAL) failed');
end;

procedure CreateWriteSecondaryBuffer(
  var Buffer: IDirectSoundBuffer; SamplesPerSec: Integer;
  Bits: Word; isStereo: Boolean; SizeInBytes: Integer);

var
  BufferDesc: DSBUFFERDESC;
  PCM: TWaveFormatEx;
begin
  FillChar(BufferDesc, SizeOf(DSBUFFERDESC), 0);
  FillChar(PCM, SizeOf(TWaveFormatEx), 0);

  with BufferDesc do
  begin
    PCM.wFormatTag := WAVE_FORMAT_PCM;

    if isStereo then
      PCM.nChannels := 2
    else
      PCM.nChannels := 1;

    PCM.nSamplesPerSec := SamplesPerSec;
    PCM.nBlockAlign := (Bits div 8) * PCM.nChannels;
    PCM.nAvgBytesPerSec := PCM.nSamplesPerSec * PCM.nBlockAlign;
    PCM.wBitsPerSample := Bits;
    PCM.cbSize := 0;

    dwSize := SizeOf(DSBUFFERDESC);
    dwFlags := DSBCAPS_STATIC;
    dwBufferBytes := SizeInBytes;//Time * PCM.nAvgBytesPerSec;
    lpwfxFormat := @PCM;
  end;

  if DirectSound.CreateSoundBuffer(BufferDesc, Buffer, nil) <> DS_OK then
    raise Exception.Create('DirectSound.CreateSoundBuffer[secondary] failed');
end;

procedure LoadWAVToSecondaryBuffer(Name: PChar; var Buffer: IDirectSoundBuffer);
var
  Data: PByteArray;
  FName: TFileStream;
  DataSize: DWord;
  Chunk: string[4];
  Pos: Integer;
begin
  FName := TFileStream.Create(Name, fmOpenRead);
  try
    Pos := 24;
    SetLength(Chunk, 4);

    repeat
      FName.Seek(Pos, soFromBeginning);
      FName.Read(Chunk[1], 4);
      Inc(Pos);
    until Chunk = 'data';

    FName.Seek(Pos + 3, soFromBeginning);
    FName.Read(DataSize, SizeOf(DWord));

    CreateWriteSecondaryBuffer(SecondarySoundBuffer, 44100, 16, False, DataSize);

    GetMem(Data, DataSize);
    try
      FName.Read(Data^, DataSize);
      WriteDataToBuffer(Buffer, 0, Data^, DataSize);
    finally
      FreeMem(Data, DataSize);
    end;
  finally
    FName.Free;
  end;
end;

begin
  FileName := Trim(ParamStr(1));
  if FileName = '' then
  begin
    WriteLn('Usage: dsplay filename.wav');
    WriteLn('The only supported format is 44100Hz 16bit mono PCM');
    Exit;
  end;

  if not FileExists(FileName) then
  begin
    WriteLn(Format('File ''%s'' doesn''t exist', [FileName]));
    Exit;
  end;

  try
    if DirectSoundCreate(nil, DirectSound, nil) <> DS_OK then
      raise Exception.Create('DirectSoundCreate failed');

    CreateWritePrimaryBuffer;
    LoadWAVToSecondaryBuffer(PWideChar(FileName), SecondarySoundBuffer);

    if SecondarySoundBuffer.Play(0, 0, 0) <> DS_OK then
      raise Exception.Create('SecondarySoundBuffer.Play failed');

    // wait till the sund has finished playing
    while True do
    begin
      Sleep(1);

      if SecondarySoundBuffer.GetStatus(Status) <> DS_OK then
        raise Exception.Create('SecondarySoundBuffer.GetStatus failed');

      if (Status <> DSBSTATUS_PLAYING) then
        Break;
    end;

    // Sleep some extra milliseconds, otherwise an audible click
    // will be heard on destroying the sound buffers
    Sleep(SLEEP_EXTRA_TIME_BEFORE_CLOSE);

  finally
    // Assign nil to variables to release their COM references
    PrimarySoundBuffer := nil;
    SecondarySoundBuffer := nil;
    DirectSound := nil;
  end;
end.



================================================
FILE: src/rec_stdout/README.md
================================================
rec_stdout.exe is a simple console utility that will record data from default input source in 44.1KHz mono 16bit signed PCM format
and write it to STDOUT.

There are two main scenarios of its use:

1) rec_stdout.exe >output.raw

This will just PCM data to an ever growing file untill you press Ctrl+C (or until the file reaches its max size).

2) rec_stdout.exe | perl test_rec_stdout.pl

This will pipe the data to any other consle application of your choice, including scripting languages.
This will allow you to examine data continuously.

================================================
FILE: src/rec_stdout/rec_stdout.dpr
================================================
// Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby

program rec_stdout;

// Uses freeware Wave Audio Package components from
// http://www.delphiarea.com/products/delphi-packages/waveaudio/

{$APPTYPE CONSOLE}

uses
  Classes,
  SysUtils,
  WaveUtils,
  WaveRecorders,
  Windows;

type
  TDataHandler = class(TObject)
    procedure LiveAudioRecorderData(Sender: TObject; const Buffer: Pointer;
      BufferSize: Cardinal; var FreeIt: Boolean);
  end;

var
  r: TLiveAudioRecorder;
  s: THandleStream;
  h: TDataHandler;

  NeedQuit: Boolean = false;

procedure TDataHandler.LiveAudioRecorderData(Sender: TObject; const Buffer: Pointer;
  BufferSize: Cardinal; var FreeIt: Boolean);
var
  i: Integer;
begin
  FreeIt := True;
  try
    s.WriteBuffer(Buffer^, BufferSize);
  except
    NeedQuit := true;
  end;
end;

procedure DispatchMessageLoop;
var
  Msg: TMsg;
begin
  while not NeedQuit and GetMessage(Msg, 0, 0, 0) do begin
    TranslateMessage(Msg);
    DispatchMessage(Msg);
    Sleep(0);
  end;
end;

begin
  try
    s := THandleStream.Create(GetStdHandle(STD_OUTPUT_HANDLE));
    h := TDataHandler.Create;
    r := TLiveAudioRecorder.Create(nil);
    r.PCMFormat := Mono16bit44100Hz;
    r.BufferLength := 100; // 100ms
    r.OnData := h.LiveAudioRecorderData;
    r.Active := true;
    DispatchMessageLoop;
    r.Active := false;
    r.WaitForStop;
  finally
    r.Free;
    h.Free;
    s.Free;
  end;
end.


================================================
FILE: src/rec_stdout/test_rec_stdout.pl
================================================
use strict;

my $buf;

my $n = 0;
for (0..10) {
    my $numread = sysread(STDIN, $buf, 10000);
    $n += $numread;
    print "$numread bytes read\n";
}

print "$n total bytes read\n";
Download .txt
gitextract_yn7l7n2u/

├── .gitignore
├── MIT-LICENSE.txt
├── README.md
├── bin/
│   ├── .gitignore
│   ├── draw-fft.pl
│   ├── furby-decode.pl
│   ├── furby-listen.bat
│   ├── furby-send.bat
│   ├── furby-send.pl
│   └── win32/
│       └── README.md
├── lib/
│   └── Furby/
│       ├── Audio.pm
│       ├── Command/
│       │   └── Dictionary.pm
│       ├── Command.pm
│       └── Packet.pm
└── src/
    ├── .gitignore
    ├── dsplay/
    │   ├── README.md
    │   └── dsplay.dpr
    └── rec_stdout/
        ├── README.md
        ├── rec_stdout.dpr
        └── test_rec_stdout.pl
Condensed preview — 20 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (69K chars).
[
  {
    "path": ".gitignore",
    "chars": 8,
    "preview": "~*\r\n~*.*"
  },
  {
    "path": "MIT-LICENSE.txt",
    "chars": 1091,
    "preview": "Copyright (c) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby\n\nPermission is hereby granted, free of charge, to an"
  },
  {
    "path": "README.md",
    "chars": 9099,
    "preview": "About Hacksby\n=============\n\n### Hacksby = Hack-a-Furby project\n\nHasbro's Furby toy (year 2012 model) uses audio protoco"
  },
  {
    "path": "bin/.gitignore",
    "chars": 6,
    "preview": "out.*\n"
  },
  {
    "path": "bin/draw-fft.pl",
    "chars": 4606,
    "preview": "#!/usr/bin/perl\n\n# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby\n\nuse strict;\n\n# only raw 16bit si"
  },
  {
    "path": "bin/furby-decode.pl",
    "chars": 5083,
    "preview": "#!/usr/bin/perl\n\n# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby\n\nuse strict;\n\n# only raw 16bit si"
  },
  {
    "path": "bin/furby-listen.bat",
    "chars": 92,
    "preview": "@echo off\r\necho Listening for Furby commands...\r\nwin32\\rec_stdout.exe | perl furby-decode.pl"
  },
  {
    "path": "bin/furby-send.bat",
    "chars": 35,
    "preview": "@perl furby-send.pl 0 --interactive"
  },
  {
    "path": "bin/furby-send.pl",
    "chars": 1816,
    "preview": "#!/usr/bin/perl\n\n# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby\n\nuse strict;\n\nBEGIN {\n    use Fil"
  },
  {
    "path": "bin/win32/README.md",
    "chars": 126,
    "preview": "See the following documents for more information on the binary utilities:\n\n../src/dsplay/README.md\n../src/rec_stdout/REA"
  },
  {
    "path": "lib/Furby/Audio.pm",
    "chars": 3767,
    "preview": "# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby\n\npackage Furby::Audio;\n\nuse strict;\n\nuse Audio::Wa"
  },
  {
    "path": "lib/Furby/Command/Dictionary.pm",
    "chars": 19396,
    "preview": "# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby\n# The dictionary data was taken from the official "
  },
  {
    "path": "lib/Furby/Command.pm",
    "chars": 8211,
    "preview": "# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby\n\npackage Furby::Command;\n\nuse Furby::Command::Dict"
  },
  {
    "path": "lib/Furby/Packet.pm",
    "chars": 3017,
    "preview": "# Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby\n\npackage Furby::Packet;\n\nuse strict;\n\nmy @checksum"
  },
  {
    "path": "src/.gitignore",
    "chars": 21,
    "preview": "*.dproj\r\n*.identcache"
  },
  {
    "path": "src/dsplay/README.md",
    "chars": 379,
    "preview": "dsplay.exe is a simple console utility to play WAV files using DirectSound. The only supported format is 44100Hz 16bit m"
  },
  {
    "path": "src/dsplay/dsplay.dpr",
    "chars": 6138,
    "preview": "// Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby\r\n\r\nprogram dsplay;\r\n\r\n// Uses DirectX 9 units fro"
  },
  {
    "path": "src/rec_stdout/README.md",
    "chars": 553,
    "preview": "rec_stdout.exe is a simple console utility that will record data from default input source in 44.1KHz mono 16bit signed "
  },
  {
    "path": "src/rec_stdout/rec_stdout.dpr",
    "chars": 1506,
    "preview": "// Copyright (C) 2013 Igor Afanasyev, https://github.com/iafan/Hacksby\r\n\r\nprogram rec_stdout;\r\n\r\n// Uses freeware Wave A"
  },
  {
    "path": "src/rec_stdout/test_rec_stdout.pl",
    "chars": 196,
    "preview": "use strict;\r\n\r\nmy $buf;\r\n\r\nmy $n = 0;\r\nfor (0..10) {\r\n    my $numread = sysread(STDIN, $buf, 10000);\r\n    $n += $numread"
  }
]

About this extraction

This page contains the full source code of the iafan/Hacksby GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 20 files (63.6 KB), approximately 21.2k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!