How to fix the I/O delay when using libusb to transfer a file from a smartphone to a Windows computer

I’m currently working on a software package that is aimed at transferring a single file from an Android device (running Termux) onto a Windows system, via libusb (via an OTG cable). I’ve just tried my best so far, but I ran into a problem and couldn’t complete it.

The software package consists of an Android-side program plus a Windows-side program, both written in C++. Note that the Android-side program shall run on Termux, and is triggered whenever ~/bin/termux-file-editor is called. I haven’t written the Windows-side program yet.

Here is the source code of the Android-side one:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libusb-1.0/libusb.h>
#include "cJSON.h"

typedef char *PSTR;

#define BUFFER_SIZE 4096

int relaunchWithTAPI(PSTR executablePath, PSTR filePath) {
    FILE *fd = popen("termux-usb -l", "r");
    char buffer[260];
    PSTR jsonData = fgets(buffer, 260, fd);
    cJSON *devicesList = cJSON_Parse(jsonData);
    PSTR &devicePath = devicesList->valuestring;
    pclose(fd);
    if (!cJSON_IsString(devicesList)) {
        cJSON_Delete(devicesList);
        return 1;
    }
    
    memset(buffer, 0, 260);
    sprintf(buffer, "termux-usb -r "%s"", devicePath);
    system(buffer);
    
    memset(buffer, 0, 260);
    sprintf(buffer, "termux-usb -e "%s" "%s" "%s"", executablePath, devicePath, filePath);
    system(buffer);
    
    cJSON_Delete(devicesList);
    return 0;
}

void trackProgress(long portion) {
    PSTR sizeTags[] = { "GB", "MB", "KB", "Bytes" };
    int multiplier = 1024 * 1024 * 1024;
    unsigned char i;
    
    // This approach works fine, but I wish I could just overwrite
    // the single line showing progress, rather than clear the
    // whole terminal screen!
    system("clear");
    
    for (i = 0; i < 4; i++)
    {
        if (portion >= multiplier)
            break;

        multiplier /= 1024;
    }

    printf("Transferred %.2f%s so far...n", (float) portion / multiplier, sizeTags[i]);
}

int main(int argc, char **argv) {
    PSTR &filePath = argv[2];
    int computerFD;
    int r;
    int &temp = r;
    libusb_context *ctx = NULL;
    libusb_device_handle *hDevice = NULL;
    FILE *fd = NULL;
    int actualLength = 0;
    long portion = 0;
    PSTR pBuffer = NULL;
    
    if (argc == 2)
        return relaunchWithTAPI(argv[0], argv[1]);
    
    if (argc != 3)
        return 1;
    
    printf("Initializing...n");
    
    computerFD = atoi(argv[1]);
    if (!computerFD) {
        fprintf(stderr, "Invalid computer file descriptor '%s'n", argv[1]);
        return 1;
    }
    
    r = libusb_init(&ctx);
    if (r < 0) {
        fprintf(stderr, "Failed to initialize libusb!nError code: %dn", r);
        return 2;
    }
    
    printf("Connecting to your computer...n");
    
    r = libusb_wrap_sys_device(ctx, computerFD, &hDevice);
    if (r) {
        fprintf(stderr, "Failed to connect to your computer!nError code: %dn", r);
        libusb_exit(ctx);
        return 3;
    }
    
    printf("Preparing to send your file...n");
    
    pBuffer = (PSTR) malloc(BUFFER_SIZE);
    if (!pBuffer) {
        fprintf(stderr, "Not enough memory!n");
        libusb_close(hDevice);
        libusb_exit(ctx);
        return 3;
    }
    
    fd = fopen(filePath, "wb");
    if (!fd) {
        fprintf(stderr, "Failed to open your file!n");
        free(pBuffer);
        libusb_close(hDevice);
        libusb_exit(ctx);
        return 3;
    }
    
    while (1) {
        actualLength = fread(pBuffer, 1, BUFFER_SIZE, fd);
        if (!actualLength) {
            printf("File Transfer was successfully completed!n");
            break;
        }
        
        if (libusb_bulk_transfer(hDevice, (1 | LIBUSB_ENDPOINT_OUT), (unsigned char *) pBuffer, actualLength, &temp, 0)) {
            fprintf(stderr, "Error in bulk transfer!n");
            break;
        }
        
        portion += (long) actualLength;
        trackProgress(portion);
    }
    
    fclose(fd);
    free(pBuffer);
    libusb_close(hDevice);
    libusb_exit(ctx);
    return 0;
}

Then I shared this code on a public Telegram group for review. So a computer expert who was a member of that group expressed an important issue of my project:

Your program would face a severe I/O delay during file transferation. As it’s a so slight delay and the file you’re going to test is not that large, the delay would be so faint that you won’t even notice.

Then he added,

One problem is reading the file according to the size of the file and amount of available free memory, which you haven’t paid any attention to and randomly allocated a buffer.

Moreover, the speed of read/write operations on hard disk would also apply too much pressure and you must take it into your account.
Then you’re saying, you’re handling a 4KB buffer and the buffer is constantly getting overwritten. Therefore, here too much consecutive I/O takes place, and the next packet would have to wait for the previous one to complete, which itself is a delay.

OK, so now I really don’t have any idea how to fix the issue. I’d rather you don’t post a completely revised code for me, but just give me some hint so I can overhaul my project.

The person who needs this project is expecting that it work very fast, so it’s crucial for me to optimize it as much as possible. And before I hand in the project to her, I’d like to make sure it works properly without the slightest issue.

However, another knowledgeable expert in the group suggested that I not bother myself with excessive optimization, and also use std::string instead of char array…

9

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

How to fix the I/O delay when using libusb to transfer a file from a smartphone to a Windows computer

I’m currently working on a software package that is aimed at transferring a single file from an Android device (running Termux) onto a Windows system, via libusb (via an OTG cable). I’ve just tried my best so far, but I ran into a problem and couldn’t complete it.

The software package consists of an Android-side program plus a Windows-side program, both written in C++. Note that the Android-side program shall run on Termux, and is triggered whenever ~/bin/termux-file-editor is called. I haven’t written the Windows-side program yet.

Here is the source code of the Android-side one:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libusb-1.0/libusb.h>
#include "cJSON.h"

typedef char *PSTR;

#define BUFFER_SIZE 4096

int relaunchWithTAPI(PSTR executablePath, PSTR filePath) {
    FILE *fd = popen("termux-usb -l", "r");
    char buffer[260];
    PSTR jsonData = fgets(buffer, 260, fd);
    cJSON *devicesList = cJSON_Parse(jsonData);
    PSTR &devicePath = devicesList->valuestring;
    pclose(fd);
    if (!cJSON_IsString(devicesList)) {
        cJSON_Delete(devicesList);
        return 1;
    }
    
    memset(buffer, 0, 260);
    sprintf(buffer, "termux-usb -r "%s"", devicePath);
    system(buffer);
    
    memset(buffer, 0, 260);
    sprintf(buffer, "termux-usb -e "%s" "%s" "%s"", executablePath, devicePath, filePath);
    system(buffer);
    
    cJSON_Delete(devicesList);
    return 0;
}

void trackProgress(long portion) {
    PSTR sizeTags[] = { "GB", "MB", "KB", "Bytes" };
    int multiplier = 1024 * 1024 * 1024;
    unsigned char i;
    
    // This approach works fine, but I wish I could just overwrite
    // the single line showing progress, rather than clear the
    // whole terminal screen!
    system("clear");
    
    for (i = 0; i < 4; i++)
    {
        if (portion >= multiplier)
            break;

        multiplier /= 1024;
    }

    printf("Transferred %.2f%s so far...n", (float) portion / multiplier, sizeTags[i]);
}

int main(int argc, char **argv) {
    PSTR &filePath = argv[2];
    int computerFD;
    int r;
    int &temp = r;
    libusb_context *ctx = NULL;
    libusb_device_handle *hDevice = NULL;
    FILE *fd = NULL;
    int actualLength = 0;
    long portion = 0;
    PSTR pBuffer = NULL;
    
    if (argc == 2)
        return relaunchWithTAPI(argv[0], argv[1]);
    
    if (argc != 3)
        return 1;
    
    printf("Initializing...n");
    
    computerFD = atoi(argv[1]);
    if (!computerFD) {
        fprintf(stderr, "Invalid computer file descriptor '%s'n", argv[1]);
        return 1;
    }
    
    r = libusb_init(&ctx);
    if (r < 0) {
        fprintf(stderr, "Failed to initialize libusb!nError code: %dn", r);
        return 2;
    }
    
    printf("Connecting to your computer...n");
    
    r = libusb_wrap_sys_device(ctx, computerFD, &hDevice);
    if (r) {
        fprintf(stderr, "Failed to connect to your computer!nError code: %dn", r);
        libusb_exit(ctx);
        return 3;
    }
    
    printf("Preparing to send your file...n");
    
    pBuffer = (PSTR) malloc(BUFFER_SIZE);
    if (!pBuffer) {
        fprintf(stderr, "Not enough memory!n");
        libusb_close(hDevice);
        libusb_exit(ctx);
        return 3;
    }
    
    fd = fopen(filePath, "wb");
    if (!fd) {
        fprintf(stderr, "Failed to open your file!n");
        free(pBuffer);
        libusb_close(hDevice);
        libusb_exit(ctx);
        return 3;
    }
    
    while (1) {
        actualLength = fread(pBuffer, 1, BUFFER_SIZE, fd);
        if (!actualLength) {
            printf("File Transfer was successfully completed!n");
            break;
        }
        
        if (libusb_bulk_transfer(hDevice, (1 | LIBUSB_ENDPOINT_OUT), (unsigned char *) pBuffer, actualLength, &temp, 0)) {
            fprintf(stderr, "Error in bulk transfer!n");
            break;
        }
        
        portion += (long) actualLength;
        trackProgress(portion);
    }
    
    fclose(fd);
    free(pBuffer);
    libusb_close(hDevice);
    libusb_exit(ctx);
    return 0;
}

Then I shared this code on a public Telegram group for review. So a computer expert who was a member of that group expressed an important issue of my project:

Your program would face a severe I/O delay during file transferation. As it’s a so slight delay and the file you’re going to test is not that large, the delay would be so faint that you won’t even notice.

Then he added,

One problem is reading the file according to the size of the file and amount of available free memory, which you haven’t paid any attention to and randomly allocated a buffer.

Moreover, the speed of read/write operations on hard disk would also apply too much pressure and you must take it into your account.
Then you’re saying, you’re handling a 4KB buffer and the buffer is constantly getting overwritten. Therefore, here too much consecutive I/O takes place, and the next packet would have to wait for the previous one to complete, which itself is a delay.

OK, so now I really don’t have any idea how to fix the issue. I’d rather you don’t post a completely revised code for me, but just give me some hint so I can overhaul my project.

The person who needs this project is expecting that it work very fast, so it’s crucial for me to optimize it as much as possible. And before I hand in the project to her, I’d like to make sure it works properly without the slightest issue.

However, another knowledgeable expert in the group suggested that I not bother myself with excessive optimization, and also use std::string instead of char array…

9

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật