This repository has been archived on 2023-10-10. You can view files and clone it, but cannot push or open issues/pull-requests.
hackfridge/terminal/tts.c

101 lines
2.6 KiB
C

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <openssl/sha.h>
#include "base64.h"
static char *g_IvonaURL = "http://www.ivona.com/online/fileSentence.php?l=en&e=0&v=1&t=%s";
void _tts_digest(char *Text, char *DigestOut)
{
unsigned char Digest[32];
SHA256_CTX SHA;
memset(Digest, 0, 32);
SHA256_Init(&SHA);
SHA256_Update(&SHA, "hf-tts", 6);
SHA256_Update(&SHA, Text, strlen(Text));
SHA256_Final(Digest, &SHA);
for (int i = 0; i < 32; i++)
sprintf(DigestOut + 2 * i, "%02x", Digest[i]);
DigestOut[64] = 0;
}
void tts_speak_cached(char *Text)
{
char CachePath[128];
strcpy(CachePath, "/tmp/hftts-");
_tts_digest(Text, CachePath + 11);
CachePath[11 + 64] = 0;
int B64OutputLength;
char *B64Output = (char *)malloc(strlen(Text) * 2);
bin_to_b64(B64Output, Text, strlen(Text));
char *URL = (char *)malloc(strlen(B64Output) + strlen(g_IvonaURL));
sprintf(URL, g_IvonaURL, B64Output);
FILE *File = fopen(CachePath, "r");
if (File)
{
printf("Cache hit on \"%s\" [%s]\n", Text, CachePath);
fclose(File);
}
else
{
printf("Cache miss on \"%s\" [%s]\n", Text, CachePath);
char *CommandLine = malloc(256);
sprintf(CommandLine, "curl -L -s -A Mozilla \"%s\" > %s", URL, CachePath);
printf("Executing %s...\n", CommandLine);
system(CommandLine);
free(CommandLine);
}
if (!fork())
{
char *CommandLineChild = malloc(strlen(URL) + 100);
sprintf(CommandLineChild, "mpg123 -2 -q %s", CachePath);
printf("Executing %s...\n", CommandLineChild);
system(CommandLineChild);
free(CommandLineChild);
printf("Child slave exiting.\n");
exit(0);
}
free((void *)URL);
free((void *)B64Output);
}
void tts_speak(char *Text)
{
int B64OutputLength;
char *B64Output = (char *)malloc(strlen(Text) * 2);
bin_to_b64(B64Output, Text, strlen(Text));
char *URL = (char *)malloc(strlen(B64Output) + strlen(g_IvonaURL));
sprintf(URL, g_IvonaURL, B64Output);
if (!fork())
{
char *CommandLine = malloc(strlen(URL) + 100);
sprintf(CommandLine, "curl -L -s -A Mozilla \"%s\" | mpg123 -2 -q -", URL);
char *Arguments[4];
Arguments[0] = "bash";
Arguments[1] = "-c";
Arguments[2] = CommandLine;
Arguments[3] = 0;
char *Environment[1];
Environment[0] = 0;
execve("/bin/bash", Arguments, Environment);
}
free((void *)URL);
free((void *)B64Output);
}