Skip to content

Commit

Permalink
fix docs and variable names
Browse files Browse the repository at this point in the history
  • Loading branch information
Your Name committed Jul 4, 2023
1 parent c3e2a47 commit 7802b53
Show file tree
Hide file tree
Showing 13 changed files with 309 additions and 16 deletions.
61 changes: 61 additions & 0 deletions internal/api/router.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package api

import (
"log"
"os"

sentryfiber "github.com/aldy505/sentry-fiber"
"github.com/getsentry/sentry-go"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/pablodz/sopro/internal/api/v2/routes"
)

func HandleRequest() {
err := sentry.Init(sentry.ClientOptions{
Dsn: os.Getenv("SENTRY_DSN"),
})
if err != nil {
log.Fatalln("sentry initialization failed")
}

log.Printf("Fiber cold start")
app := fiber.New()

// Middleware: cors
app.Use(cors.New(cors.Config{
AllowOrigins: "*",
AllowHeaders: "authorization,Content-Type",
AllowMethods: "GET,POST,PUT,DELETE,OPTIONS",
AllowCredentials: true,
}))

// Middleware: sentry
app.Use(sentryfiber.New(sentryfiber.Options{
WaitForDelivery: false, // don't block lambda execution
}))

// Middleare: Logger
app.Use(logger.New(logger.Config{
Done: func(c *fiber.Ctx, logString []byte) {
if c.Response().StatusCode() != fiber.StatusOK {
sentry.CaptureMessage(string(logString))
}
},
}))

// Middleware: Recover
app.Use(recover.New())

app = Router(app)

log.Fatal(app.Listen(":9898"))
}

func Router(app *fiber.App) *fiber.App {
routes.HealthRoutes(app)
routes.TranscodingRoutes(app)
return app
}
6 changes: 6 additions & 0 deletions internal/api/v2/endpoints/endpoints.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package endpoints

// Health
const HEALTH = "/health"

const TRANSCODING = "/api/v2/transcoding"
11 changes: 11 additions & 0 deletions internal/api/v2/routes/health.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package routes

import (
"github.com/gofiber/fiber/v2"
"github.com/pablodz/sopro/internal/api/v2/endpoints"
"github.com/pablodz/sopro/internal/api/v2/services/health"
)

func HealthRoutes(app *fiber.App) {
app.Get(endpoints.HEALTH, func(c *fiber.Ctx) error { return health.Ping(c) })
}
11 changes: 11 additions & 0 deletions internal/api/v2/routes/transcoding.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package routes

import (
"github.com/gofiber/fiber/v2"
"github.com/pablodz/sopro/internal/api/v2/endpoints"
"github.com/pablodz/sopro/internal/api/v2/services/transcoding"
)

func TranscodingRoutes(app *fiber.App) {
app.Post(endpoints.TRANSCODING, func(c *fiber.Ctx) error { return transcoding.TranscodeFile(c) })
}
12 changes: 12 additions & 0 deletions internal/api/v2/services/health/health.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package health

import (
"log"

"github.com/gofiber/fiber/v2"
)

func Ping(c *fiber.Ctx) error {
log.Println("[Health][Ping]")
return c.SendString("Pong!")
}
104 changes: 104 additions & 0 deletions internal/api/v2/services/transcoding/transcoding.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package transcoding

import (
"bytes"
"os"

"github.com/gofiber/fiber/v2"
"github.com/pablodz/sopro/pkg/audioconfig"
"github.com/pablodz/sopro/pkg/cpuarch"
"github.com/pablodz/sopro/pkg/encoding"
"github.com/pablodz/sopro/pkg/fileformat"
"github.com/pablodz/sopro/pkg/method"
"github.com/pablodz/sopro/pkg/sopro"
"github.com/pablodz/sopro/pkg/transcoder"
)

func TranscodeFile(c *fiber.Ctx) error {

// get the uploaded file from the request
file, err := c.FormFile("audio")
if err != nil {
return err
}

// open the uploaded file
in, err := file.Open()
if err != nil {
return err
}
defer in.Close()

// read in as buffer and pass to data
buf := make([]byte, file.Size)
if _, err := in.Read(buf); err != nil {
return err
}

// convert to bytes buffer
data := bytes.NewBuffer(buf)

// Create the output file
out, err := os.Create("./internal/samples/output.wav")
if err != nil {
panic(err)
}
defer out.Close()

// create a transcoder
t := &transcoder.Transcoder{
MethodT: method.BIT_LOOKUP_TABLE,
InConfigs: sopro.AudioConfig{
Endianness: cpuarch.LITTLE_ENDIAN,
},
OutConfigs: sopro.AudioConfig{
Endianness: cpuarch.LITTLE_ENDIAN,
},
SizeBuffer: 1024,
Verbose: true,
}

// Transcode the file
err = t.Mulaw2Wav(
&sopro.In{
Data: data,
AudioFileGeneral: sopro.AudioFileGeneral{
Format: fileformat.AUDIO_MULAW,
Config: audioconfig.MulawConfig{
BitDepth: 8,
Channels: 1,
Encoding: encoding.SPACE_LOGARITHMIC, // ulaw is logarithmic
SampleRate: 8000,
},
},
},
&sopro.Out{
Data: out,
AudioFileGeneral: sopro.AudioFileGeneral{
Format: fileformat.AUDIO_WAV,
Config: audioconfig.WavConfig{
BitDepth: 8,
Channels: 1,
Encoding: encoding.SPACE_LOGARITHMIC,
SampleRate: 8000,
},
},
},
)

if err != nil {
panic(err)
}

// set the response header to indicate that a file is being returned
c.Set(fiber.HeaderContentType, "audio/mpeg")
c.Set(fiber.HeaderContentDisposition, "attachment; filename=processed-audio.wav")

// send the processed audio file to the client
if err := c.SendFile(out.Name()); err != nil {
return err
}

// return nil to indicate success
return c.SendStatus(fiber.StatusOK)
}
7 changes: 7 additions & 0 deletions internal/server/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package server

import "github.com/pablodz/sopro/internal/api"

func Serve() {
api.HandleRequest()
}
7 changes: 7 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package main

import "github.com/pablodz/sopro/internal/server"

func main() {
server.Serve()
}
76 changes: 76 additions & 0 deletions pkg/soprocli/transcoding.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package soprocli

import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
)

func TranscodeFile() {
// create a new HTTP client
client := &http.Client{}

// open the audio file to be uploaded
file, err := os.Open("audio.mp3")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()

// create a new multipart form
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)

// add the audio file to the form
part, err := writer.CreateFormFile("audio", "audio.mp3")
if err != nil {
fmt.Println(err)
return
}
if _, err := io.Copy(part, file); err != nil {
fmt.Println(err)
return
}

// close the multipart form
if err := writer.Close(); err != nil {
fmt.Println(err)
return
}

// create a new HTTP request
req, err := http.NewRequest("POST", "http://localhost:3000/process-audio", body)
if err != nil {
fmt.Println(err)
return
}
req.Header.Set("Content-Type", writer.FormDataContentType())

// send the HTTP request and get the response
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()

// save the processed audio file to disk
file, err = os.Create("processed-audio.mp3")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()

// read the response body and write it to the processed audio file
if _, err := io.Copy(file, resp.Body); err != nil {
fmt.Println(err)
return
}

fmt.Println("Audio file processed successfully")
}
22 changes: 10 additions & 12 deletions pkg/transcoder/decoder/decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@ package decoder

import "fmt"

// DecodeFrameUlaw2Lpcm Decodes only raw bytes (no headers)
// from ulaw to linear pcm
// log pcm -> linear pcm
// 8 bit log pcm (ulaw) -> 16 bit linear pcm
func DecodeFrameUlaw2Lpcm(pcm []byte) ([]byte, error) {
if len(pcm) == 0 {
return []byte{}, fmt.Errorf("pcm is empty")
// DecodeULawToPCM decodes raw ULaw-encoded audio data to linear PCM.
// Each ULaw frame is 8-bit logarithmic PCM, which is converted to 16-bit linear PCM.
func DecodeULawToPCM(ulaw []byte) ([]byte, error) {
if len(ulaw) == 0 {
return []byte{}, fmt.Errorf("ulaw is empty")
}
lpcm := make([]byte, len(pcm)*2)
for i, frame := range pcm {
lpcmFrame := ulaw2lpcm[frame]
copy(lpcm[i*2:], []byte{byte(lpcmFrame), byte(lpcmFrame >> 8)})
pcm := make([]byte, len(ulaw)*2)
for i, ulawFrame := range ulaw {
pcmFrame := ulawToPcmTable[ulawFrame]
copy(pcm[i*2:], []byte{byte(pcmFrame), byte(pcmFrame >> 8)})
}
return lpcm, nil
return pcm, nil
}
2 changes: 1 addition & 1 deletion pkg/transcoder/decoder/decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func TestDecodeUlaw2Lpcm(t *testing.T) {
},
}
for _, tt := range tests {
lpcm, err := DecodeFrameUlaw2Lpcm(tt.logPcm)
lpcm, err := DecodeULawToPCM(tt.logPcm)
if (err != nil) != tt.wantErr {
t.Errorf("unexpected error: %v", err)
continue
Expand Down
4 changes: 2 additions & 2 deletions pkg/transcoder/decoder/lookup_tables.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package decoder

// ulaw2lpcm is a lookup table for u-law to LPCM
var ulaw2lpcm = [256]int16{
// ulawToPcmTable is a lookup table for u-law to LPCM
var ulawToPcmTable = [256]int16{
-32124, -31100, -30076, -29052, -28028, -27004, -25980, -24956,
-23932, -22908, -21884, -20860, -19836, -18812, -17788, -16764,
-15996, -15484, -14972, -14460, -13948, -13436, -12924, -12412,
Expand Down
2 changes: 1 addition & 1 deletion pkg/transcoder/system_transcoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func differentSpaceEncoding(in *sopro.In, out *sopro.Out, transcoder *Transcoder
}
bufIn = bufIn[:n]
// buf2 is different size than buf
bufOut, _ = decoder.DecodeFrameUlaw2Lpcm(bufIn) // IMPORTANT:buf cut to n bytes
bufOut, _ = decoder.DecodeULawToPCM(bufIn) // IMPORTANT:buf cut to n bytes
out.Length += len(bufOut)
if _, err = out.Writer.Write(bufOut); err != nil {
return nTotal, fmt.Errorf("error writing output file: %v", err)
Expand Down

0 comments on commit 7802b53

Please sign in to comment.