Optimizing CD reader using libcdio in c

55 views Asked by At

I have a USB CD reader connected to my PC. This program reads a given track of the CD using libcdio and writes it to a binary file using command ./readcd <track_num> on Linux. When run right now it transfers at a speed of about 1 mb/s, which is obviously very slow compared to the bandwidth of a USB 3.0 connection. My question is are there any obvious ways to speed this up significantly? My PC is relatively good(i7-12700H), so it shouldn't be the problem. This is my the code for the CD reader as of now:

#include <stdio.h>
#include <stdlib.h>
#include <cdio/cdio.h>
#include <cdio/track.h>
#include <cdio/cd_types.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <integer>\n", argv[0]);
        return 1;
    }

    track_t track_num = atoi(argv[1]);
    // Open the default CD drive
    CdIo_t *cdio = cdio_open(NULL, DRIVER_UNKNOWN);
    if (!cdio) {
        fprintf(stderr, "No CD drive found\n");
        return 1;
    }

    // Ensure the track number is valid
    track_t first_track = cdio_get_first_track_num(cdio);
    track_t last_track = cdio_get_num_tracks(cdio);
    if (track_num < first_track || track_num > last_track) {
        fprintf(stderr, "Track number is invalid\n");
        cdio_destroy(cdio);
        return 1;
    }
    if (!cdio_get_track_format(cdio, track_num) == TRACK_FORMAT_AUDIO) {
        fprintf(stderr, "The track is not an audio track\n");
        cdio_destroy(cdio);
        return 1;
    }
    char fileName[100];
    snprintf(fileName, 100, "Track_%d.raw", track_num);
    FILE *file = fopen(fileName, "wb");
    if (!file) {
        fprintf(stderr, "Unable to open file for writing\n");
        cdio_destroy(cdio);
        return 1;
    }

    // Read and output the track data
    lsn_t start_lsn = cdio_get_track_lsn(cdio, track_num);
    lsn_t end_lsn = cdio_get_track_last_lsn(cdio, track_num);
    for (lsn_t lsn = start_lsn; lsn <= end_lsn; ++lsn) {
        // Read a sector
        u_int8_t buf[CDIO_CD_FRAMESIZE_RAW] = {0};
        if (cdio_read_audio_sector(cdio, buf, lsn) != DRIVER_OP_SUCCESS) {
            fprintf(stderr, "Error reading audio sector at LSN: %d\n", lsn);
            continue;
        }

        // Output the binary data of the buffer
        fwrite(buf, sizeof(buf), 1, file);
    }

    // Cleanup
    fclose(file);
    cdio_destroy(cdio);
    return 0;
}

Uses to the cdio_read_audio_sector function to fill up an array of bytes, which is the written to the binary file.

I tried using multiprocessing pthreads, but it occurred to me, that a cd cant read multiple audio sectors at a time, because it only has 1 sensor. I dont exactly know what is taking the most time here but it's most likely cdio_read_audio_sector(cdio, buf, lsn) or fwrite(buf, sizeof(buf), 1, file);

0

There are 0 answers