Exemple #1
0
/**
 * \brief write a message to a client
 * \param mt is the minstack_tcp stack
 * \param cid is the client ID to whom send the message, if 0 the message is broadcast to the clients
 * \param message is the message
 * \param len_message is the length of the message
 * \return 0 if OK
 */
int minstack_tcp_write_to_client(minstack_tcp *mt, int cid, char *message,
        int len_message) {
    //without cid we send the message to all the clients
    if (!mt) {
        //printerror("the minstack_tcp is NULL\n");
        return -100;
    }
    if (mt->type != SERVER) {
        printwarning("The minstack is not a server...\n");
        return -1;
    }
    if (mt->status != STARTED) {
        printwarning("The server is not started yet\n");
        return -1;
    }
    if (cid)
        return minstack_tcp_write(mt, cid, message, len_message);
    else {
        int i, retval = 0;
        for (i = 0; i < mt->sockets.connected_client_nb; i++) {
            retval = minstack_tcp_write(mt, mt->sockets.client_socket_fd[0],
                    message, len_message);
            if (retval) {
                printerror("We had a problem sending to the client %d\n",i);
                return retval;
            }
        }
    }
    return 0;
}
void graphicssdlrender_startFrame(void) {
#ifdef USE_SDL_GRAPHICS_OPENGL_EFFECTS
    if (maincontext) {
        GLenum err;
        if ((err = glGetError()) != GL_NO_ERROR) {
            printwarning("graphicsrender_startFrame: earlier error "
                "around: %s", gluErrorString(err));
        }

        renderts = time_getMilliseconds();

        glClearColor(0, 0, 0, 1);
        glClear(GL_COLOR_BUFFER_BIT);
        if ((err = glGetError()) != GL_NO_ERROR) {
            printwarning("graphicsrender_startFrame: "
                "glClear error: %s", gluErrorString(err));
        }

        glDisable(GL_DEPTH_TEST);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();

        int actualwidth, actualheight;
        SDL_GetWindowSize(mainwindow, &actualwidth, &actualheight);
        glOrtho(0, actualwidth, actualheight, 0, -1, 1);
        return;
    }
#endif
    SDL_SetRenderDrawColor(mainrenderer, 0, 0, 0, 1);
    SDL_RenderClear(mainrenderer);
}
static int graphicsrender_drawCropped_GL(
        struct graphicstexture *gt, int x, int y, float alpha,
        unsigned int sourcex, unsigned int sourcey,
        unsigned int sourcewidth, unsigned int sourceheight,
        unsigned int drawwidth, unsigned int drawheight,
        int rotationcenterx, int rotationcentery, double rotationangle,
        int horiflipped,
        double red, double green, double blue, int textureFiltering) {
    // source UV coords:
    assert(gt->width >= 0);
    assert(gt->height >= 0);
    double sx = ((double)sourcex) / (double)gt->width;
    double sy = ((double)sourcey) / (double)gt->height;
    double sw = ((double)sourcewidth) / (double)gt->width;
    double sh = ((double)sourceheight) / (double)gt->height;
    assert(sw >= 0);
    assert(sh >= 0);

    GLenum err;
    if ((err = glGetError()) != GL_NO_ERROR) {
        printwarning("graphicsrender_drawCropped_GL: "
            "lingering error before render: %s",
            glGetErrorString(err));
    }

    glEnable(GL_TEXTURE_2D);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); 
    glPushMatrix();
    // apply sprite rotation:
    glTranslatef((x + drawwidth * 0.5), (y + drawheight * 0.5), 0);
    glRotated(rotationangle, 0, 0, 1);
    glTranslatef(-(x + drawwidth * 0.5), -(y + drawheight * 0.5),
        -(0));
    // draw sprite:
    if (graphicstexture_bindGl(gt, renderts)) {
        glBegin(GL_QUADS);

        glTexCoord2f(sx, sy + sh); 
        glVertex2d(x, y + drawheight);
        glTexCoord2f(sx + sw, sy + sh);
        glVertex2d(x + drawwidth, y + drawheight);
        glTexCoord2f(sx + sw, sy);
        glVertex2d(x + drawwidth, y);
        glTexCoord2f(sx, sy);
        glVertex2d(x, y);

        glEnd();
    }
    glPopMatrix();
    glDisable(GL_BLEND);
    if ((err = glGetError()) != GL_NO_ERROR) {
        printwarning("graphicsrender_drawCropped_GL: "
            "error after render: %s",
            glGetErrorString(err));
    }
    return 1;
}
Exemple #4
0
/**
 * \brief write a message to the server where we are connected
 * \param mt is the minstack_tcp stack
 * \param message is the message
 * \param len_message is the length of the message
 * \return 0 if OK
 */
int minstack_tcp_write_to_server(minstack_tcp *mt, char *message, int len_message) {
    if (!mt) {
        //printerror("the minstack_tcp is NULL\n");
        return -100;
    }
    if (mt->type != CLIENT) {
        printwarning("The minstack is not a server...\n");
        return -1;
    }
    if (mt->status != STARTED) {
        printwarning("The client is not started yet\n");
        return -1;
    }
    return minstack_tcp_write(mt,mt->listen_socket_fd, message, len_message);
}
Exemple #5
0
/**
 * \brief Start the minstack_tcp in parameter
 * \param mt the minstack_tcp that have to be started
 * \return 0 if the minstack_tcp stack started correctly
 */
int minstack_tcp_start(minstack_tcp *mt) {
    int retval = 0;
    if (!mt || mt->status != IDLE) {
        printerror("Cannot start while already started\n");
        return -1;
    }
    switch (mt->type) {
    case NONE:
        printwarning("the minstack_tcp is not initialized\n");
        return -1;
    case SERVER:
        retval = minstack_tcp_boot_server(mt);
        break;
    case CLIENT:
        retval = minstack_tcp_boot_client(mt);
        break;
    default:
        printerror("Unknow enum type %d\n",mt->type);
        break;
    }
    if (!retval) {
        mt->status = STARTED;
        printmessage("%s is now started\n",mt->name);
    }
    return retval;
}
struct graphicstexture *graphicstexture_createHWSDL(
        struct graphicstexture *gt,
        void *data,
        size_t width, size_t height, int format, uint64_t time) {
    // create hw texture
#ifdef DEBUGUPLOADTIMING
    uint64_t ts1 = time_getMilliseconds();
#endif
    gt->sdltex = SDL_CreateTexture(mainrenderer,
        graphicstexture_pixelFormatToSDLFormat(format),
        SDL_TEXTUREACCESS_STREAMING,
        gt->width, gt->height);
    if (!gt->sdltex) {
        graphicstexture_destroy(gt);
        return NULL;
    }
#ifdef DEBUGUPLOADTIMING
    uint64_t ts2 = time_getMilliseconds();
#endif

    // lock texture
    void *pixels;
    int pitch;
    if (SDL_LockTexture(gt->sdltex, NULL, &pixels, &pitch) != 0) {
        graphicstexture_destroy(gt);
        return NULL;
    }
#ifdef DEBUGUPLOADTIMING
    uint64_t ts3 = time_getMilliseconds();
#endif

    // copy pixels into texture
    memcpy(pixels, data, gt->width * gt->height * 4);
    // FIXME: we probably need to handle pitch here??

#ifdef DEBUGUPLOADTIMING
    uint64_t ts4 = time_getMilliseconds();
#endif

    // unlock texture
    SDL_UnlockTexture(gt->sdltex);

#ifdef DEBUGUPLOADTIMING
    uint64_t ts5 = time_getMilliseconds();
    if (ts5-ts1 > 100) {
        printwarning("[sdltex] texture upload duration: %dms total, "
            "%dms creation, %dms lock, %dms copy, %dms unlock",
            (int)(ts5-ts1), (int)(ts2-ts1), (int)(ts3-ts2),
            (int)(ts4-ts3), (int)(ts5-ts4));
    }
#endif

    // set blend mode
    SDL_SetTextureBlendMode(gt->sdltex, SDL_BLENDMODE_BLEND);

    return gt;
}
Exemple #7
0
void main_InitAudio(void) {
#ifdef USE_AUDIO
    if (audioinitialised) {
        return;
    }
    audioinitialised = 1;

    // get audio backend
    char* p = luastate_GetPreferredAudioBackend();

    // load FFmpeg if we happen to want it
    if (luastate_GetWantFFmpeg()) {
        audiosourceffmpeg_LoadFFmpeg();
    } else {
        audiosourceffmpeg_DisableFFmpeg();
    }

#if defined(USE_SDL_AUDIO) || defined(WINDOWS)
    char* error;

    // initialise audio - try 32bit first
    s16mixmode = 0;
#ifndef FORCES16AUDIO
    if (!audio_Init(&audiomixer_GetBuffer, 0, p, 0, &error)) {
        if (error) {
            free(error);
        }
#endif
        // try 16bit now
        s16mixmode = 1;
        if (!audio_Init(&audiomixer_GetBuffer, 0, p, 1, &error)) {
            printwarning("Warning: Failed to initialise audio: %s", error);
            if (error) {
                free(error);
            }
            // non-fatal: we will simulate audio manually:
            simulateaudio = 1;
            s16mixmode = 0;
        }
#ifndef FORCES16AUDIO
    }
#endif
    if (p) {
        free(p);
    }
#else  // USE_SDL_AUDIO || WINDOWS
    // simulate audio:
    simulateaudio = 1;
    s16mixmode = 0;
#endif  // USE_SDL_AUDIO || WINDOWS
#else // ifdef USE_AUDIO
    // we don't support any audio
    return;
#endif  // ifdef USE_AUDIO
}
Exemple #8
0
int pop(void)
{
	if(empty())
	{
		printwarning("Stack Underflow");
		return -1;
	}
	int y = array[stacksize];
	stacksize = stacksize - 1;
	return y;
}
Exemple #9
0
void graphics_GetDesktopVideoMode(int* x, int* y) {
    char* error;
    *x = 0;
    *y = 0;
    if (!graphics_InitVideoSubsystem(&error)) {
        printwarning("Failed to initialise video subsystem: %s", error);
        if (error) {
            free(error);
        }
        return;
    }

    // -> do this with SDL per default
    SDL_DisplayMode m;
    if (SDL_GetDesktopDisplayMode(0, &m) == 0) {
        *x = m.w;
        *y = m.h;
    } else {
        printwarning("Unable to determine desktop video mode: %s", SDL_GetError());
    }
}
Exemple #10
0
static void loadorwarn(void **ptr, void *lib, const char *name) {
    if (loadorfailstate) {
        return;
    }
    *ptr = library_GetSymbol(lib, name);
    if (!*ptr) {
#ifdef FFMPEGDEBUG
        printwarning("Warning: [FFmpeg-debug] Failed to load unimportant "
            "symbol: %s", name);
#endif
    }
}
Exemple #11
0
/*
 * take ressources because pthread_cancel do not free the memory allocation
 * but we have to cancel the thread because we can stay in accept wait event if we try to use a non blocked socket
 */
void *minstack_tcp_accept_thread(void *ptr) {
    minstack_tcp *mt = (minstack_tcp *) ptr;
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

    printdebug("starting %s\n",__FUNCTION__);
    while (!mt->pthread_accept_thread_stop) {
        int tmp_clisockfd;
        unsigned int cli_len;
        struct sockaddr_in cli_addr;

        memset((char *) &cli_addr, 0, sizeof(cli_addr));
        cli_len = sizeof(cli_addr);
#ifdef WIN32
        tmp_clisockfd = accept(mt->listen_socket_fd, (struct sockaddr *) &cli_addr,(int *) &cli_len);
#else
        tmp_clisockfd = accept(mt->listen_socket_fd, (struct sockaddr *) &cli_addr, &cli_len);
#endif
        if (tmp_clisockfd == -1) {
            usleep(mt->receive_loop_usleep);
            continue;
        } else if (tmp_clisockfd <= 0) {
            printerror("error :%d\n",tmp_clisockfd);
            printmoreerror("ERROR on accept:");
            break;
        }
        pthread_mutex_lock(&mt->mutex);
        mt->sockets.client_socket_fd[mt->sockets.connected_client_nb]
                = tmp_clisockfd;
        mt->sockets.connected_client_nb++;
        pthread_mutex_unlock(&mt->mutex);
        mt->new_connection_callback(tmp_clisockfd, &cli_addr);
        if (mt->pthread_reading_thread_stop && pthread_create(
                &mt->pthread_reading_thread, NULL, minstack_tcp_reading_thread,
                (void *) mt)) {
            printwarning("pthread_create minstack_tcp_accept_thread error\n");
            continue;
        }
    }
    //TODO what is this ?!!!
    //before was //if (mt->pthread_reading_thread && !mt->pthread_reading_thread) {
    if (&mt->pthread_reading_thread && !mt->pthread_reading_thread_stop){
        mt->pthread_reading_thread_stop = 1;
        pthread_join(mt->pthread_reading_thread, NULL);
        printmessage("The reading thread stopped\n");
    }
    printdebug("stopping %s\n",__FUNCTION__);
    pthread_exit(NULL);
    return NULL;
}
int graphicstexture_getDesiredFormat(void) {
#ifdef USE_SDL_GRAPHICS_OPENGL_EFFECTS
    if (maincontext) {
        return PIXELFORMAT_32BGRA;
    }
#endif
    SDL_RendererInfo rinfo;
    if (SDL_GetRendererInfo(mainrenderer, &rinfo) == 0) {
        unsigned int i = 0;
        while (i < rinfo.num_texture_formats) {
            int pixelformat = graphicstexture_SDLFormatToPixelFormat(
                rinfo.texture_formats[i]);
            if (pixelformat != PIXELFORMAT_UNKNOWN) {
                if (!infoprinted) {
                    infoprinted = 1;
                    printinfo("[sdltex] Pixel format found: %d\n",
                        pixelformat);
                }
                return pixelformat;
            }
            i++;
        }
        if (!infoprinted) {
            printinfo("[sdltex] no known pixel format in %d "
                "supported formats of renderer", rinfo.
                num_texture_formats);
        } 
    } else {
        printwarning("[sdltex] SDL_GetRendererInfo call failed: %s",
            SDL_GetError());
    }
    if (!infoprinted) {
        infoprinted = 1;
        printwarning("[sdltex] cannot find optimal pixel format!");
    }
    return PIXELFORMAT_32RGBA;
}
Exemple #13
0
void graphicssdlrender_completeFrame(void) {
#ifdef USE_SDL_GRAPHICS_OPENGL_EFFECTS
    if (maincontext) {
        SDL_GL_SwapWindow(mainwindow);
        GLenum err;
        if ((err = glGetError()) != GL_NO_ERROR) {
            printwarning("graphicsrender_completeFrame: "
                "error after SDL_GL_SwapWindow: %s",
                glGetErrorString(err));
        }
        return;
    }
#endif
    SDL_RenderPresent(mainrenderer);
}
Exemple #14
0
/**
 * \brief Uninitialized a minstack_tcp
 * \param mt is the minstack_tcp stack
 */
void minstack_tcp_uninit(minstack_tcp *mt) {
    if (!mt) {
        printwarning("Trying to uninit a NULL minstack_tcp\n");
        return;
    }
    if (mt->status == STARTED) {
        minstack_tcp_stop(mt);
        printdebug("%s minstack has TCP been stopped before uninit\n",mt->name);
    }
    printmessage("%s minstack TCP has been uninitialized\n",mt->name);
    free(mt);
#ifdef WIN32
    win32_uninit_socket_api();
#endif
}
Exemple #15
0
/**
 * \brief Boot the minstack_tcp in client mode
 * \param mt the minstack_tcp that have to be boot
 * \return 0 if the minstack_tcp stack boot correctly
 */
int minstack_tcp_boot_client(minstack_tcp *mt) {
    struct sockaddr_in serv_addr;
    struct hostent *server;
    if (!mt)
        return -1;

    mt->listen_socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (mt->listen_socket_fd < 0) {
        printmoreerror("ERROR opening socket:");
        return -2;
    }
    server = gethostbyname(mt->address);
    if (server == NULL) {
        fprintf(stderr, "ERROR, no such host :%s\n",mt->address);
        return -3;
    }
    memset((char *) &serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
#ifndef WIN32
    bcopy((char *) server->h_addr, (char *) &serv_addr.sin_addr.s_addr,
            server->h_length);
#else
    memcpy( (char *) &serv_addr.sin_addr.s_addr,(char *) server->h_addr,
            server->h_length);
#endif
    serv_addr.sin_port = htons(mt->port);
    if (connect(mt->listen_socket_fd, (const struct sockaddr *) &serv_addr,
            (socklen_t) sizeof(serv_addr)) < 0) {
        printmoreerror("ERROR connecting:");
        return -4;
    }
    if (mt->external_read_socket == NULL) {
        printdebug("We do not start the reading thread in client mode because no external interpretation is done\n");
        mt->pthread_accept_thread_stop = 1;
        mt->pthread_reading_thread_stop = 1;
        return 0;
    }
    mt->sockets.client_socket_fd[0] = mt->listen_socket_fd;
    mt->sockets.connected_client_nb = 1;
    mt->pthread_accept_thread_stop = 1;//because it will not run
    if (pthread_create(&mt->pthread_reading_thread, NULL,
            minstack_tcp_reading_thread, (void *) mt)) {
        printwarning("pthread_create minstack_tcp_accept_thread error\n");
        return -5;
    }
    return 0;
}
Exemple #16
0
int graphics_GetNumberOfVideoModes() {
    char* error;
    if (!graphics_InitVideoSubsystem(&error)) {
        printwarning("Failed to initialise video subsystem: %s", error);
        if (error) {
            free(error);
        }
        return 0;
    }
    graphics_ReadVideoModes();
    int i = 0;
    while (videomodesx && videomodesx[i] > 0
            && videomodesy && videomodesy[i] > 0) {
        i++;
    }
    return i;
}
Exemple #17
0
/**
 * \brief Boot the minstack_tcp in server mode
 * \param mt the minstack_tcp that have to be boot
 * \return 0 if the minstack_tcp stack boot correctly
 */
int minstack_tcp_boot_server(minstack_tcp *mt) {
    struct sockaddr_in serv_addr;

    if (!mt)
        return -1;
    pthread_mutex_lock(&mt->mutex);
    mt->listen_socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (mt->listen_socket_fd < 0) {
        printmoreerror("ERROR opening socket:");
        return -2;
    }
#ifndef WIN32
    if (fcntl(mt->listen_socket_fd, F_SETFL, O_NONBLOCK) < 0) {
        printmoreerror("Could not O_NONBLOCK:");
        return -3;
    }
#else
    {
        u_long imode = 1;
        if(ioctlsocket(mt->listen_socket_fd,FIONBIO,&imode)  < 0) {
            printmoreerror("Could not O_NONBLOCK:");
            return -3;
        }
    }
#endif
    memset((char *) &serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(mt->port);
    if (bind(mt->listen_socket_fd, (const struct sockaddr *) &serv_addr,
            (socklen_t) sizeof(serv_addr)) < 0) {
        printmoreerror("ERROR connecting");
        pthread_mutex_unlock(&mt->mutex);
        return -4;
    }
    listen(mt->listen_socket_fd, (int) mt->max_client_nb);
    if (pthread_create(&mt->pthread_accept_thread, NULL, minstack_tcp_accept_thread, mt)) {
        printwarning("pthread_create minstack_tcp_boot_server error\n");
        pthread_mutex_unlock(&mt->mutex);
        return -5;
    }
    pthread_mutex_unlock(&mt->mutex);
    printdebug("%s started.\n",__FUNCTION__);
    return 0;
}
Exemple #18
0
static int graphicsrender_drawCropped_GL(
        struct graphicstexture *gt, int x, int y, float alpha,
        unsigned int sourcex, unsigned int sourcey,
        unsigned int sourcewidth, unsigned int sourceheight,
        unsigned int drawwidth, unsigned int drawheight,
        int rotationcenterx, int rotationcentery, double rotationangle,
        int horiflipped,
        double red, double green, double blue, int textureFiltering) {
    // source UV coords:
    double sx = sourcex / (double)gt->width;
    double sy = sourcey / (double)gt->height;
    double sw = sourcewidth / (double)gt->width;
    double sh = sourceheight / (double)gt->height;

    glEnable(GL_TEXTURE_2D);
    glPushMatrix();
    glRotated((rotationangle / M_PI) * 180, x + drawwidth / 2,
        0, y + drawwidth / 2);
    glActiveTexture(GL_TEXTURE0);
    if (graphicstexture_bindGl(gt, renderts)) {
        glBegin(GL_QUADS);
        glVertex2d(x, y);
        glVertex2d(x, y + drawheight);
        glVertex2d(x + drawwidth, y + drawheight);
        glVertex2d(x + drawwidth, y);       
        glEnd();
    }
    glPopMatrix();
    GLenum err;
    if ((err = glGetError()) != GL_NO_ERROR) {
        printwarning("graphicsrender_drawCropped_GL: "
            "error after render: %s",
            gluErrorString(err));
    }
    return 1;
}
Exemple #19
0
int SDL_main(int argc, char** argv) {
#else
#ifdef WINDOWS
int CALLBACK WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
#else
int main(int argc, char** argv) {
#endif
#endif
    thread_MarkAsMainThread();

#if defined(ANDROID) || defined(__ANDROID__)
    printinfo("Blitwizard %s starting", VERSION);
#endif

    // set signal handlers:
    signalhandling_Init();

    // set path to blitwizard binary:
#ifdef UNIX
    if (argc > 0) {
        binpath = file_GetAbsolutePathFromRelativePath(argv[0]);
    }
#endif

    // test crash handling:
    //*((int*)5) = 2;

    // evaluate command line arguments:
    const char* script = "game.lua";
    int scriptargfound = 0;
    int option_changedir = 0;
    char* option_templatepath = NULL;
    int nextoptionistemplatepath = 0;
    int nextoptionisscriptarg = 0;
    int gcframecount = 0;

#ifdef WINDOWS
    // obtain command line arguments a special way on windows:
    int argc = __argc;
    char** argv = __argv;
#endif

    // we want to store the script arguments so we can pass them to lua:
    char** scriptargs = malloc(sizeof(char*) * MAXSCRIPTARGS);
    if (!scriptargs) {
        printerror("Error: failed to allocate script args space");
        return 1;
    }
    int scriptargcount = 0;

    // parse command line arguments:
    int i = 1;
    while (i < argc) {
        if (!scriptargfound) { // pre-scriptname arguments
            // process template path option parameter:
            if (nextoptionistemplatepath) {
                nextoptionistemplatepath = 0;
                if (option_templatepath) {
                    free(option_templatepath);
                }
                option_templatepath = strdup(argv[i]);
                if (!option_templatepath) {
                    printerror("Error: failed to strdup() template "
                    "path argument");
                    main_Quit(1);
                    return 1;
                }
                file_MakeSlashesNative(option_templatepath);
                i++;
                continue;
            }

            // various options:
            if ((argv[i][0] == '-' || strcasecmp(argv[i],"/?") == 0)
            && !nextoptionisscriptarg) {
                if (strcasecmp(argv[i], "--") == 0) {
                    // this enforces the next arg to be the script name:
                    nextoptionisscriptarg = 1;
                    i++;
                    continue;
                }

                if (strcasecmp(argv[i],"--help") == 0 || strcasecmp(argv[i], "-help") == 0
                || strcasecmp(argv[i], "-?") == 0 || strcasecmp(argv[i],"/?") == 0
                || strcasecmp(argv[i],"-h") == 0) {
                    printf("blitwizard %s (C) 2011-2013 Jonas Thiem et al\n",
                    VERSION);
                    printf("Usage:\n   blitwizard [blitwizard options] "
                           "[script name] [script options]\n\n");
                    printf("The script name should be a .lua file containing\n"
                    "Lua source code for use with blitwizard.\n\n");
                    printf("The script options (optional) are passed through\n"
                    "to the script.\n\n");
                    printf("Supported blitwizard options:\n");
                    printf("   -changedir             Change working directory to "
                           "the\n"
                           "                          folder of the script\n");
                    printf("   -help                  Show this help text and quit\n");
                    printf("   -templatepath [path]   Check another place for "
                           "templates\n"
                           "                          (not the default "
                           "\"templates/\")\n");
                    printf("   -version               Show extended version info and quit\n");
                    return 0;
                }
                if (strcasecmp(argv[i], "-changedir") == 0) {
                    option_changedir = 1;
                    i++;
                    continue;
                }
                if (strcasecmp(argv[i], "-templatepath") == 0) {
                    nextoptionistemplatepath = 1;
                    i++;
                    continue;
                }
                if (strcmp(argv[i], "-v") == 0 || strcasecmp(argv[i], "-version") == 0
                || strcasecmp(argv[i], "--version") == 0) {
                    printf("blitwizard %s (C) 2011-2013 Jonas Thiem et al\n",VERSION);
                    printf("\nSupported features of this build:\n");

                    #ifdef USE_SDL_AUDIO
                    printf("  Audio device: SDL 2\n");
                    #else
                    #ifdef USE_AUDIO
                    #ifdef WINDOWS
                    printf("  Audio device: waveOut\n");
                    #else
                    printf("  Audio device: only virtual (not audible)\n");
                    #endif
                    #else
                    printf("  Audio device: no\n");
                    printf("     Playback support: none, audio disabled\n");
                    printf("     Resampling support: none, audio disabled\n");
                    #endif
                    #endif

                    #if (defined(USE_SDL_AUDIO) || defined(USE_AUDIO))
                    printf("     Playback support: Ogg (libogg)%s%s\n",
                    #if defined(USE_FLAC_AUDIO)
                    ", FLAC (libFLAC)"
                    #else
                    ""
                    #endif
                    ,
                    #if defined(USE_FFMPEG_AUDIO)
                    #ifndef USE_FLAC_AUDIO
                    ", FLAC (FFmpeg),\n      mp3 (FFmpeg), WAVE (FFmpeg), mp4 (FFmpeg),\n      many more.. (FFmpeg)\n     (Please note FFmpeg can fail to load at runtime,\n     resulting in FFmpeg playback support not working)"
                    #else
                    ",\n      mp3 (FFmpeg), WAVE (FFmpeg), mp4 (FFmpeg),\n      many more.. (FFmpeg)\n     (Please note FFmpeg can fail to load at runtime,\n      resulting in FFmpeg playback support not working)"
                    #endif
                    #else
                    ""
                    #endif
                    );
                    #if defined(USE_SPEEX_RESAMPLING)
                    printf("     Resampling: libspeex\n");
                    #else
                    printf("     Resampling: none (non-48kHz audio will sound wrong!)\n");
                    #endif
                    #endif

                    #ifdef USE_GRAPHICS
                    #ifdef USE_SDL_GRAPHICS
                    #ifdef USE_OGRE_GRAPHICS
                    printf("  Graphics device: SDL 2, Ogre\n");
                    printf("     2d graphics support: SDL 2, Ogre\n");
                    printf("     3d graphics support: Ogre\n");
                    #else
                    printf("  Graphics device: SDL 2\n");
                    printf("     2d graphics support: SDL 2\n");
                    printf("     3d graphics support: none\n");
                    #endif
                    #else
                    printf("  Graphics device: only virtual (not visible)\n");
                    printf("     2d graphics support: virtual\n");
                    printf("     3d graphics support: none\n");
                    #endif
                    #else
                    printf("  Graphics device: none\n");
                    printf("     2d graphics support: none, graphics disabled\n");
                    printf("     3d graphics support: none, graphics disabled\n");
                    #endif
                    #if defined(USE_PHYSICS2D) || defined(USE_PHYSICS3D)
                    printf("  Physics: yes\n");
                    #else
                    printf("  Physics: no\n");
                    #endif
                    #if defined(USE_PHYSICS2D)
                    printf("     2d physics: Box2D\n");
                    #else
                    printf("     2d physics: none\n");
                    #endif
                    #if defined(USE_PHYSICS3D)
                    printf("     3d physics: bullet\n");
                    #else
                    printf("     3d physics: none\n");
                    #endif
                    #if defined(USE_PHYSFS)
                    printf("  .zip archive resource loading: yes\n");
                    #else
                    printf("  .zip archive resource loading: no\n");
                    #endif     

                    printf("\nVarious build options:\n");
                    printf("  SYSTEM_TEMPLATE_PATH:\n   %s\n",
                    SYSTEM_TEMPLATE_PATH);
                    #if defined(USE_LIB_FLAGS)
                    printf("  FINAL_USE_LIB_FLAGS:\n   %s\n",
                    USE_LIB_FLAGS);
                    #endif

                    printf("\nCheck out http://www.blitwizard.de/"
                    " for info about blitwizard.\n");

                    fflush(stdout);
                    exit(0);
                }
                printwarning("Warning: Unknown Blitwizard option: %s", argv[i]);
            } else {
                scriptargfound = 1;
                script = argv[i];
            }
        } else {
            // post-scriptname arguments -> store them for Lua
            if (scriptargcount < MAXSCRIPTARGS) {
                scriptargs[scriptargcount] = strdup(argv[i]);
                scriptargcount++;
            }
        }
        i++;
    }

#ifdef USE_AUDIO
    // This needs to be done at some point before we actually 
    // initialise audio so that the mixer is ready for use then
    audiomixer_Init();
#endif

    // check the provided path:
    char outofmem[] = "Out of memory";
    char* error;
    char* filenamebuf = NULL;

#if defined(ANDROID) || defined(__ANDROID__)
    printinfo("Blitwizard startup: locating lua start script...");
#endif

    // if no template path was provided, default to "templates/"
    if (!option_templatepath) {
        option_templatepath = strdup("templates/");
        if (!option_templatepath) {
            printerror("Error: failed to allocate initial template path");
            main_Quit(1);
            return 1;
        }
        file_MakeSlashesNative(option_templatepath);
    }

    // load internal resources appended to this binary,
    // so we can load the game.lua from it if there is any inside:
#ifdef WINDOWS
    // windows
    // try encrypted first:
    if (!resources_LoadZipFromOwnExecutable(NULL, 1)) {
        // ... ok, then attempt unencrypted:
        resources_LoadZipFromOwnExecutable(NULL, 0);
    }
#else
#ifndef ANDROID
    // unix systems
    // encrypted first:
    if (!resources_LoadZipFromOwnExecutable(argv[0], 1)) {
        // ... ok, then attempt unencrypted:
        resources_LoadZipFromOwnExecutable(argv[0], 0);
    }
#endif
#endif

    // check if provided script path is a folder:
    if (file_IsDirectory(script)) {
        // make sure it isn't inside a resource file as a proper file:
        if (!resources_LocateResource(script, NULL)) {
            // it isn't, so we can safely assume it is a folder.
            // -> append "game.lua" to the path
            if (filenamebuf) {
                free(filenamebuf);
            }
            filenamebuf = file_AddComponentToPath(script, "game.lua");
            if (!filenamebuf) {
                printerror("Error: failed to add component to script path");
                main_Quit(1);
                return 1;
            }
            script = filenamebuf;
        }
    }

    // check if script file is internal resource or disk file
    int scriptdiskfile = 0;
    struct resourcelocation s;
    if (!resources_LocateResource(script, &s)) {
        printerror("Error: cannot locate script file \"%s\"", script);
        main_Quit(1);
        return 1;
    } else {
        if (s.type == LOCATION_TYPE_ZIP) {
            scriptdiskfile = 0;
        } else{
            scriptdiskfile = 1;
        }
    }
 
    // compose game.lua path variable (for os.gameluapath())
    if (scriptdiskfile) {
        gameluapath = file_GetAbsolutePathFromRelativePath(script);
    } else {
        gameluapath = strdup(script);
    }
    if (!gameluapath) { // string allocation failed
        printerror("Error: failed to allocate script path (gameluapath)");
        main_Quit(1);
        return 1;
    } else {
        if (gameluapath) {
            file_MakeSlashesCrossplatform(gameluapath);
        }
    }

    // check if we want to change directory to the provided script path:
    if (option_changedir) {
        char* p = file_GetAbsoluteDirectoryPathFromFilePath(script);
        if (!p) {
            printerror("Error: NULL returned for absolute directory");
            main_Quit(1);
            return 1;
        }
        char* newfilenamebuf = file_GetFileNameFromFilePath(script);
        if (!newfilenamebuf) {
            free(p);
            printerror("Error: NULL returned for file name");
            main_Quit(1);
            return 1;
        }
        if (filenamebuf) {
            free(filenamebuf);
        }
        filenamebuf = newfilenamebuf;
        if (!file_Cwd(p)) {
            free(filenamebuf);
            printerror("Error: Cannot cd to \"%s\"", p);
            free(p);
            main_Quit(1);
            return 1;
        }
        free(p);
        script = filenamebuf;
    }
      
/*#if defined(ANDROID) || defined(__ANDROID__)
    printinfo("Blitwizard startup: Preparing graphics framework...");
#endif

    // initialise graphics
#ifdef USE_GRAPHICS
    if (!graphics_Init(&error)) {
        printerror("Error: Failed to initialise graphics: %s",error);
        free(error);
        fatalscripterror();
        main_Quit(1);
        return 1;
    }
    sdlinitialised = 1;
#endif*/

#if defined(ANDROID) || defined(__ANDROID__)
    printinfo("Blitwizard startup: Initialising physics...");
#endif

#ifdef USE_PHYSICS2D
    // initialise physics
    physics2ddefaultworld = physics_createWorld(0);
    if (!physics2ddefaultworld) {
        printerror("Error: Failed to initialise Box2D physics");
        fatalscripterror();
        main_Quit(1);
        return 1;
    }
    luacfuncs_object_initialisePhysicsCallbacks();
#endif

#if defined(ANDROID) || defined(__ANDROID__)
    printinfo("Blitwizard startup: Reading templates if present...");
#endif

    // Search & run templates. Separate code for desktop/android due to
    // android having the templates in embedded resources (where cwd'ing to
    // isn't supported), while for the desktop it is a regular folder.
#if !defined(ANDROID)
    int checksystemwidetemplate = 1;
    // see if the template path points to a virtual zip folder:
    if (resource_IsFolderInZip(option_templatepath)) {
        // it does. run templates from here.
        checksystemwidetemplate = 0;
        if (!attemptTemplateLoad(option_templatepath)) {
            checksystemwidetemplate = 1;
        }
    } else {
        // see if there is a template directory & file:
        if (file_DoesFileExist(option_templatepath)
        && file_IsDirectory(option_templatepath)) {
            checksystemwidetemplate = 0;

            // now run template file:
            if (!attemptTemplateLoad(option_templatepath)) {
                checksystemwidetemplate = 1;
            }
        }
    }
#if defined(SYSTEM_TEMPLATE_PATH)
    if (checksystemwidetemplate) {
        attemptTemplateLoad(SYSTEM_TEMPLATE_PATH);
    }
#endif
#else // if !defined(ANDROID)
    // on Android, we only allow templates/init.lua.
    // see if we can read the file:
    int exists = 0;
    SDL_RWops* rwops = SDL_RWFromFile("templates/init.lua", "rb");
    if (rwops) {
        exists = 1;
        rwops->close(rwops);
    }
    if (exists) {
        // run the template file:
        attemptTemplateLoad("templates/");
    }
#endif

    // free template dir now that we've loaded things:
    free(option_templatepath);


#if defined(ANDROID) || defined(__ANDROID__)
    printinfo("Blitwizard startup: Executing lua start script...");
#endif

    // push command line arguments into script state:
    i = 0;
    int pushfailure = 0;
    while (i < scriptargcount) {
        if (!luastate_PushFunctionArgumentToMainstate_String(scriptargs[i])) {
            pushfailure = 1;
            break;
        }
        i++;
    }
    if (pushfailure) {
        printerror("Error: Couldn't push all script arguments into script state");
        main_Quit(1);
        return 1;
    }

    // free arguments:
    i = 0;
    while (i < scriptargcount) {
        free(scriptargs[i]);
        i++;
    }
    free(scriptargs);

    // open and run provided script file and pass the command line arguments:
    if (!luastate_DoInitialFile(script, scriptargcount, &error)) {
        if (error == NULL) {
            error = outofmem;
        }
        printerror("Error: an error occured when running \"%s\": %s", script, error);
        if (error != outofmem) {
            free(error);
        }
        fatalscripterror();
        main_Quit(1);
        return 1;
    }

    // enable blitwizard.onLog
    doConsoleLog();

#if defined(ANDROID) || defined(__ANDROID__)
    printinfo("Blitwizard startup: Calling blitwiz.on_init...");
#endif
    doConsoleLog();

    // call init
    if (!luastate_CallFunctionInMainstate("blitwizard.onInit", 0, 1, 1,
    &error, NULL, NULL)) {
        printerror("Error: An error occured when calling blitwizard.onInit: %s",error);
        if (error != outofmem) {
            free(error);
        }
        fatalscripterror();
        main_Quit(1);
        return 1;
    }
    doConsoleLog();

    // when graphics or audio is open, run the main loop
#if defined(ANDROID) || defined(__ANDROID__)
    printinfo("Blitwizard startup: Entering main loop...");
#endif
    doConsoleLog();

    // Initialise audio when it isn't
    main_InitAudio();
    doConsoleLog();

    // If we failed to initialise audio, we want to simulate it
#ifdef USE_AUDIO
    uint64_t simulateaudiotime = 0;
    if (simulateaudio) {
        simulateaudiotime = time_GetMilliseconds();
    }
#endif

    uint64_t logictimestamp = time_GetMilliseconds();
    uint64_t lastdrawingtime = 0;
    uint64_t physicstimestamp = time_GetMilliseconds();
    while (!wantquit) {
        doConsoleLog(); 
        uint64_t timeNow = time_GetMilliseconds();

        // this is a hack for SDL bug http://bugzilla.libsdl.org/show_bug.cgi?id=1422

#ifdef USE_AUDIO
        // simulate audio
        if (simulateaudio) {
            while (simulateaudiotime < time_GetMilliseconds()) {
                char buf[48 * 4 * 2];
                audiomixer_GetBuffer(buf, 48 * 4 * 2);
                simulateaudiotime += 1; // 48 * 1000 times * 4 bytes * 2 channels per second = simulated 48kHz 32bit stereo audio
            }
        }
#endif // ifdef USE_AUDIO

        // check for unused, no longer playing media objects:
        checkAllMediaObjectsForCleanup();

        // slow sleep: check if we can safe some cpu by waiting longer
        unsigned int deltaspan = TIMESTEP;
#ifndef USE_GRAPHICS
        int nodraw = 1;
#else
        int nodraw = 1;
        if (graphics_AreGraphicsRunning()) {
            nodraw = 0;
        }
#endif
        // see how much time as already passed since the last frame:
        uint64_t delta = time_GetMilliseconds()-lastdrawingtime;

        // sleep/limit FPS as much as we can
        if (delta < (deltaspan-10)) {
            // the time passed is smaller than the optimal waiting time
            // -> sleep
            if (connections_NoConnectionsOpen() &&
            !listeners_HaveActiveListeners()) {
                // no connections, use regular sleep
                time_Sleep((deltaspan-10)-delta);
                connections_SleepWait(0);
            } else {
                // use connection select wait to get connection events
                connections_SleepWait(deltaspan-delta);
            }
        } else {
            // the time passed exceeds the optimal waiting time already
            // -> don't slow down at all
            connections_SleepWait(0);  // check on connections
        }

        // Remember drawing time and process net events
        lastdrawingtime = time_GetMilliseconds();
        if (!luafuncs_ProcessNetEvents()) {
            // there was an error processing the events
            main_Quit(1);
        }

#ifdef USE_GRAPHICS
        // check and trigger all sort of input events
        graphics_CheckEvents(&quitevent, &mousebuttonevent, &mousemoveevent, &keyboardevent, &textevent, &putinbackground);
#endif
        doConsoleLog();

        // call the step function and advance physics
        int physicsiterations = 0;
        int logiciterations = 0;
        time_t iterationStart = time(NULL);
#if defined(USE_PHYSICS2D)
        int psteps2d_max = ((float)TIMESTEP/
        (float)physics_getStepSize(physics2ddefaultworld));
        psteps2d_max++;
#endif
        while (
        // allow maximum of iterations in an attempt to keep up:
        (logictimestamp < timeNow || physicstimestamp < timeNow) &&
        (logiciterations < MAXLOGICITERATIONS
#if defined(USE_PHYSICS2D) || defined(USE_PHYSICS3D)
 ||  physicsiterations < MAXPHYSICSITERATIONS
#endif
        )
        // .. unless we're already doing this for >2 seconds:
        && iterationStart + 2 >= time(NULL)
            ) {
#ifdef USE_PHYSICS2D
            if (physicsiterations < MAXPHYSICSITERATIONS &&
            physicstimestamp < timeNow && (physicstimestamp <= logictimestamp
            || logiciterations >= MAXLOGICITERATIONS)) {
                int psteps = psteps2d_max;
                while (psteps > 0) {
                    physics_step(physics2ddefaultworld);
                    physicstimestamp += physics_getStepSize(
                        physics2ddefaultworld);
                    psteps--;
                }
                physicsiterations++;
            }
#else
            physicstimestamp = timeNow + 2000;
#endif
            if (logiciterations < MAXLOGICITERATIONS &&
            logictimestamp < timeNow && (logictimestamp <= physicstimestamp
            || physicsiterations >= MAXPHYSICSITERATIONS)) {
                // check how much logic we might want to do in a batch:
                int k = (timeNow-logictimestamp)/TIMESTEP;
                if (k > MAXBATCHEDLOGIC) {
                    k = MAXBATCHEDLOGIC;
                }
                // call logic functions of all objects:
                int i = luacfuncs_object_doAllSteps(k);
                doConsoleLog();

                // advance time step:
                logictimestamp += i * TIMESTEP;
                logiciterations += i;
            }
        }

        // check if we ran out of iterations:
        if (logiciterations >= MAXLOGICITERATIONS ||
        physicsiterations >= MAXPHYSICSITERATIONS
        || iterationStart + 2 < time(NULL)) {
            if (
#if defined(USE_PHYSICS2D) || defined(USE_PHYSICS3D)
                    physicstimestamp < timeNow ||
#endif
                 logictimestamp < timeNow) {
                // we got a problem: we aren't finished,
                // but we hit the iteration limit
                physicstimestamp = time_GetMilliseconds();
                logictimestamp = time_GetMilliseconds();
                printwarning("Warning: logic is too slow, maximum logic iterations have been reached (%d)", (int)MAXLOGICITERATIONS);
            } else {
                // we don't need to iterate anymore -> everything is fine
            }
        }

#ifdef USE_GRAPHICS
        // report visibility of sprites to texture manager:
        graphics2dsprites_reportVisibility();
#endif

#ifdef USE_GRAPHICS
        // texture manager tick:
        texturemanager_tick();
#endif

        // update object graphics:
        luacfuncs_object_updateGraphics();
        doConsoleLog();

#ifdef USE_GRAPHICS
        if (graphics_AreGraphicsRunning()) {
#ifdef ANDROID
            if (!appinbackground) {
#endif
                // draw a frame
                graphicsrender_Draw();
#ifdef ANDROID
            }
#endif
        }
#endif

        // we might want to quit if there is nothing else to do
#ifdef USE_AUDIO
        if (
#ifdef USE_GRAPHICS
        !graphics_AreGraphicsRunning() &&
#endif
        connections_NoConnectionsOpen() &&
        !listeners_HaveActiveListeners() && audiomixer_NoSoundsPlaying()) {
#else
        if (
#ifdef USE_GRAPHICS
        !graphics_AreGraphicsRunning() &&
#endif
        connections_NoConnectionsOpen() &&
        !listeners_HaveActiveListeners()) {
#endif
            main_Quit(1);
        }

#ifdef USE_GRAPHICS
        // be very sleepy if in background
        if (appinbackground) {
#ifdef ANDROID
            time_Sleep(40);
#endif
        }
#endif

        // do some garbage collection:
        /*gcframecount++;
        if (gcframecount > 100) {
            // do a gc step once in a while
            luastate_GCCollect();
        }*/

        // new frame:
#ifdef USE_GRAPHICS
        luacfuncs_objectgraphics_newFrame();
#endif
    }
    main_Quit(0);
    return 0;
}
struct graphicstexture *graphicstexture_createHWPBO(
        struct graphicstexture *gt,
        void *data,
        size_t width, size_t height, int format, uint64_t time) {
    // clear OpenGL error:
    while (glGetError() != GL_NO_ERROR) {glGetError();}
    
    GLenum err;
    glGenBuffers(1, &gt->pboid);
    if ((err = glGetError()) != GL_NO_ERROR) {
        gt->pboid = 0;
        printwarning("graphicstexture_createHWPBO: PBO creation: "
            "glGenBuffers failed");
        goto failure;
    }
    // bind buffer and fill
    glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, gt->pboid);
    if ((err = glGetError()) != GL_NO_ERROR) {
        printwarning("graphicstexture_createHWPBO: PBO CREATION: "
            "glBindBuffer failed");
        goto failure;
    }
    glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, width * height * 4,
        data, GL_STREAM_DRAW_ARB);
    if ((err = glGetError()) != GL_NO_ERROR) {
        printwarning("graphicstexture_createHWPBO: PBO creation: "
            "glBufferData failed");
        goto failure;
    }

    // create a new texture:
    glGenTextures(1, &gt->texid);
    if ((err = glGetError()) != GL_NO_ERROR) {
        gt->texid = 0;
        printwarning("graphicstexture_createHWPBO: texture creation: "
            "glGenTextures failed");
        goto failure;
    }
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
    if ((err = glGetError()) != GL_NO_ERROR) {
        gt->texid = 0;
        printwarning("graphicstexture_createHWPBO: texture creation: "
        "glTexParameteri failed (GL_TEXTURE_BASE_LEVEL)");
        goto failure;
    }
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
    if ((err = glGetError()) != GL_NO_ERROR) {
        gt->texid = 0;
        printwarning("graphicstexture_createHWPBO: texture creation: "
            "glTexParameteri failed (GL_TEXTURE_MAX_LEVEL)");
        goto failure;
    }

    // transfer PBO to texture:
    glBindTexture(GL_TEXTURE_2D, gt->texid);
    if ((err = glGetError()) != GL_NO_ERROR) {
        printwarning("graphicstexture_createHWPBO: transfer: "
            "glBindTexture failed");
        goto failure;
    }
    glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, gt->pboid);
    if ((err = glGetError()) != GL_NO_ERROR) {
        printwarning("graphicstexture_createHWPBO: transfer: "
            "glBindBuffer failed");
        goto failure;
    }
    glTexImage2D(GL_TEXTURE_2D,
        0, GL_RGBA, width, height, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8,
        0);
    if ((err = glGetError()) != GL_NO_ERROR) {
        printwarning("graphicstexture_createHWPBO: transfer: "
            "glTexImage2D failed");
        goto failure;
    }
    return gt;

failure:
    printwarning("graphicstexture_createHWPBO: failed; OpenGL "
        "error string is: %s", gluErrorString(err));
    // clean up all error bits:
    while (glGetError() != GL_NO_ERROR) {glGetError();}
    // destroy texture:
    graphicstexture_destroy(gt);
    return NULL;
}
Exemple #21
0
static int audiosourceffmpeg_read(struct audiosource *source, char *buffer, unsigned int bytes) {
    struct audiosourceffmpeg_internaldata *idata = source->internaldata;

    if (idata->eof) {
        return -1;
    }

    if (!audiosourceffmpeg_loadFFmpeg()) {
        audiosourceffmpeg_fatalError(source);
        return -1;
    }

    if (!idata->codeccontext) {
        // Get format context
        idata->formatcontext = ffmpeg_avformat_alloc_context();
        if (!idata->formatcontext) {
            audiosourceffmpeg_fatalError(source);
            return -1;
        }

        // av_dict_set(&codec_opts, "request_channels", "2", 0);
        // opts = setup_find_stream_info_opts(ic, codec_opts);

        // Get IO context and buffers
        if (!idata->aviobuf) {
            idata->aviobuf = ffmpeg_av_malloc(AVIOBUFSIZE);
            if (!idata->aviobuf) {
                audiosourceffmpeg_fatalError(source);
                return -1;
            }
        }
        idata->iocontext = ffmpeg_avio_alloc_context(idata->aviobuf, AVIOBUFSIZE, 0, source, ffmpegreader, NULL, NULL);
        if (!idata->iocontext) {
            audiosourceffmpeg_fatalError(source);
            return -1;
        }
        idata->formatcontext->pb = idata->iocontext;
        idata->formatcontext->iformat = NULL;

        // Read format
        if (ffmpeg_avformat_open_input(
                &idata->formatcontext, "", NULL, NULL) != 0) {
            audiosourceffmpeg_fatalError(source);
            return -1;
        }

        // Read detailed stream info
        int i = 0;
        if (ffmpeg_avformat_find_stream_info) {
            // new FFmpeg with avformat_find_stream_info
            if ((i = ffmpeg_avformat_find_stream_info(idata->formatcontext,
            NULL)) < 0) {
                audiosourceffmpeg_fatalError(source);
                return -1;
            }
        } else {
            // old FFmpeg
            if (ffmpeg_av_find_stream_info(idata->formatcontext) < 0) {
                audiosourceffmpeg_fatalError(source);
                return -1;
            }
        }

        // Find best stream
        int stream;
        if (ffmpeg_av_find_best_stream) {
            // use the awesome FFmpeg function
            stream = ffmpeg_av_find_best_stream(idata->formatcontext,
            AVMEDIA_TYPE_AUDIO, -1, -1, &idata->audiocodec, 0);
        } else {
            // simply take the first audio stream
            unsigned int i = 0;
            stream = 0;
            while (i < idata->formatcontext->nb_streams) {
                if (idata->formatcontext->streams[i]->codec->codec_type
                        == AVMEDIA_TYPE_AUDIO) {
                    stream = i;
                    break;
                }
                i++;
            }
        }
        if (stream < 0) {
            audiosourceffmpeg_fatalError(source);
            return -1;
        }

        // Get codec context
        struct AVCodecContext* c =
            idata->formatcontext->streams[stream]->codec;

        // Find best codec, we don't trust av_find_best_stream on this for now
        idata->audiocodec = ffmpeg_avcodec_find_decoder(c->codec_id);
        if (!idata->audiocodec) {
            // Format is recognised, but codec unsupported
            audiosourceffmpeg_fatalError(source);
            return -1;
        }

        // If this isn't an audio stream, we don't want it:
        if (c->codec_type != AVMEDIA_TYPE_AUDIO) {
            audiosourceffmpeg_fatalError(source);
            return -1;
        }

        // Get our actual codec context:
        /*if (ffmpeg_avcodec_alloc_context3) {
            // new FFmpeg with avcodec_alloc_context3
            idata->codeccontext = ffmpeg_avcodec_alloc_context3(idata->audiocodec);
        } else {
            // old FFmpeg
            idata->codeccontext = ffmpeg_avcodec_alloc_context();
        }*/
        idata->codeccontext = c;

        // Initialise codec. XXX avcodec_open2 is not thread-safe!
        if (ffmpeg_avcodec_open2(idata->codeccontext, idata->audiocodec, NULL) < 0) {
            audiosourceffmpeg_fatalError(source);
            return -1;
        }

        // Allocate buffer for finished, decoded data
        if (!idata->decodedbuf) {
            idata->decodedbuf = ffmpeg_av_malloc(DECODEDBUFSIZE);
            if (!idata->decodedbuf) {
                audiosourceffmpeg_fatalError(source);
                return -1;
            }
        }

        // Remember format data
        source->channels = c->channels;
        source->samplerate = c->sample_rate;
        switch (c->sample_fmt) {
        case AV_SAMPLE_FMT_U8:
            source->format = AUDIOSOURCEFORMAT_U8;
            break;
        case AV_SAMPLE_FMT_S16:
            source->format = AUDIOSOURCEFORMAT_S16LE;
            break;
        case AV_SAMPLE_FMT_FLT:
            source->format = AUDIOSOURCEFORMAT_F32LE;
            break;
        default:
            audiosourceffmpeg_fatalError(source);
            return -1;
        }
        if (source->channels <= 1 || source->samplerate <= 0) {
#ifdef FFMPEGDEBUG
            printwarning("[FFmpeg-debug] format probing failed: channels "
                "or sample rate unknown or unsupported");
#endif
            // not a known format apparently
            audiosourceffmpeg_fatalError(source);
            return -1;
        }
#ifdef FFMPEGDEBUG
        printinfo("[FFmpeg-debug] audiostream initialised: rate: %d, "
            "channels: %d, format: %d", source->samplerate, source->channels,
            source->format);
#endif
    }

    // we need to return how many bytes we read, so remember it here:
    int writtenbytes = 0;

    // we might have some decoded bytes left:
    if (idata->decodedbufbytes > 0 && bytes > 0) {
        // see how many we want to copy and how many we can actually copy:
        int copybytes = bytes;

        if (copybytes > idata->decodedbufbytes) {
            copybytes = idata->decodedbufbytes;
        }

        // copy bytes to passed buffer:
        memcpy(buffer, idata->decodedbuf, copybytes);
        buffer += copybytes;

        // trim copied bytes from our internal buffer of decoded data:
        if (copybytes < idata->decodedbufbytes) {
            memmove(idata->decodedbuf, idata->decodedbuf + copybytes,
                DECODEDBUFSIZE - copybytes);
        }

        idata->decodedbufbytes -= copybytes;
        bytes -= copybytes;
        writtenbytes += copybytes;
    }

    while (bytes > 0 && !idata->packetseof) {
        int packetresult = -1;
        if (!idata->packetseof) { // fetch new packet
            packetresult = ffmpeg_av_read_frame(idata->formatcontext,
                &idata->packet);
        }
        if (packetresult == 0) {
            // decode with FFmpeg:
            int len,gotframe;
            char *outputbuf __attribute__ ((aligned(16)));
            int bufsize = 0;
            // old variant: decode_audio3:
            if (!ffmpeg_avcodec_decode_audio4) {
                if (!idata->tempbuf) {
                    idata->tempbuf = ffmpeg_av_malloc(
                    AVCODEC_MAX_AUDIO_FRAME_SIZE + 32);
                    outputbuf = idata->tempbuf;
                }

                bufsize = AVCODEC_MAX_AUDIO_FRAME_SIZE + 16;
                gotframe = 0;
                len = ffmpeg_avcodec_decode_audio3(
                    idata->codeccontext,
                    (int16_t*)outputbuf,
                    &bufsize,
                    &idata->packet
                );
                if (len > 0) {
                    gotframe = 1;
                }
            } else {
                // new variant: decode_audio4:
                len = ffmpeg_avcodec_decode_audio4(
                    idata->codeccontext,
                    idata->decodedframe,
                    &gotframe,
                    &idata->packet
                );
            }

            if (len < 0) {
                // A decode error occured:
#ifdef FFMPEGDEBUG
                char errbuf[512] = "Unknown";
                if (ffmpeg_av_strerror) {
                    ffmpeg_av_strerror(len, errbuf, sizeof(errbuf)-1);
                }
                errbuf[sizeof(errbuf)-1] = 0;
                printwarning("[FFmpeg-debug] avcodec_decode_audio3 error: "
                    "%s",errbuf);
#endif
                if (ffmpeg_av_read_frame(
                        idata->formatcontext, &idata->packet) < 0) {
                    // buggy FFmpeg EOF
#ifdef FFMPEGDEBUG
                    printwarning("[FFmpeg-debug] buggy FFmpeg EOF");
#endif
                    idata->packetseof = 1;
                    return writtenbytes;
                }
                audiosourceffmpeg_fatalError(source);
                return -1;
            }else{
                if (len == 0) {
                    idata->packetseof = 1;
                }
            }

            // return data if we have some
            if (gotframe) {
                int framesize;  // amount of bytes
                const char *p;  // pointer to byte data
                if (!ffmpeg_avcodec_decode_audio4) {
                    // old variant: decode_audio3:
                    framesize = bufsize;
                    p = outputbuf;
                } else {
                    // new variant: decode_audio4:
                    framesize = ffmpeg_av_samples_get_buffer_size(
                    NULL,
                    idata->codeccontext->channels,
                    idata->decodedframe->nb_samples,
                    idata->codeccontext->sample_fmt,
                    1);
                    p = (char*)idata->decodedframe->data[0];
                }

                // first, export as much as we can
                if (bytes > 0) {
                    // ideally, we would copy the whole frame:
                    unsigned int copybytes = framesize;

                    // practically, we don't want more than what is specified
                    // in 'bytes':
                    if (copybytes > bytes) {
                        copybytes = bytes;
                    }

                    // copy the bytes, move the buffers accordingly:
                    memcpy(buffer, p, copybytes);
                    buffer += copybytes;
                    bytes -= copybytes;
                    framesize -= copybytes;
                    p += copybytes;
                    writtenbytes += copybytes;
                }

                // maximal preserval size:
                if (framesize > DECODEDBUFSIZE) {
                    // we will simply crop the frame.
                    // evil but the show must go on
                    framesize = DECODEDBUFSIZE;
                }

                // if we have any bytes left, preserve them now:
                if (framesize > 0) {
                    memcpy(idata->decodedbuf + idata->decodedbufbytes, p,
                        framesize);
                    idata->decodedbufbytes += framesize;
                }
            }
        }else{
Exemple #22
0
static int graphicsrender_drawCropped_SDL(
        struct graphicstexture *gt, int x, int y, float alpha,
        unsigned int sourcex, unsigned int sourcey,
        unsigned int sourcewidth, unsigned int sourceheight,
        unsigned int drawwidth, unsigned int drawheight,
        int rotationcenterx, int rotationcentery, double rotationangle,
        int horiflipped,
        double red, double green, double blue, int textureFiltering) {
    // calculate source dimensions
    SDL_Rect src,dest;
    src.x = sourcex;
    src.y = sourcey;
    src.w = sourcewidth;
    src.h = sourceheight;

    // set target dimensinos
    dest.x = x;
    dest.y = y;
    dest.w = drawwidth;
    dest.h = drawheight;    

    // set alpha mod:
    int i = (int)((float)255.0f * alpha);
    if (SDL_SetTextureAlphaMod(gt->sdltex, i) < 0) {
        printwarning("Warning: Cannot set texture alpha "
        "mod %d: %s\n", i, SDL_GetError());
    }

    // calculate rotation center:
    SDL_Point p;
    p.x = (int)((double)rotationcenterx * ((double)drawwidth / src.w));
    p.y = (int)((double)rotationcentery * ((double)drawheight / src.h));

    // set draw color:
    SDL_SetTextureColorMod(gt->sdltex, (red * 255.0f),
        (green * 255.0f), (blue * 255.0f));

    // set texture filter:
    if (!textureFiltering) {
        // disable texture filter
        /* SDL_SetHintWithPriority(SDL_HINT_RENDER_SCALE_QUALITY,
        "0", SDL_HINT_OVERRIDE); */

        // this doesn't work. we will need to wait for:
        // https://bugzilla.libsdl.org/show_bug.cgi?id=2167
    }

    // actual draw call:
    if (horiflipped) {
        // draw rotated and flipped
        SDL_RenderCopyEx(mainrenderer, gt->sdltex, &src, &dest,
            rotationangle, &p, SDL_FLIP_HORIZONTAL);
    } else {
        if (rotationangle > 0.001 || rotationangle < -0.001) {
            // draw rotated
            SDL_RenderCopyEx(mainrenderer, gt->sdltex, &src, &dest,
            rotationangle, &p, SDL_FLIP_NONE);
        } else {
            // don't rotate the rendered image if it's barely rotated
            // (this helps the software renderer)
            SDL_RenderCopy(mainrenderer, gt->sdltex, &src, &dest);
        }
    }
    if (!textureFiltering) {
        // re-enable texture filter
        SDL_SetHintWithPriority(SDL_HINT_RENDER_SCALE_QUALITY,
        "1", SDL_HINT_OVERRIDE);
    }
    return 1;
}
Exemple #23
0
void printerror(const char* msg)
{
	printwarning(msg);
	abort();
}
void parsecommand(char* s){
	int clength = 0;
	int error = 0;
	int hasParameter = 0;
	getCommand(s);
	clength = strlen(shellbuff.command);
	if(shellbuff.buffer[clength]==' '){
		hasParameter = 1;
		getParameter(shellbuff.buffer, clength);
	}
	// Execute the requested command 
	if(!strcmp(shellbuff.command,"test")){
		error = s_test(hasParameter, shellbuff.parameter);
	}
	if(!strcmp(shellbuff.command,"help")){
		error = s_help(hasParameter, shellbuff.parameter);
	}
	else if(!strcmp(shellbuff.command, "reboot")){
		error = s_reboot(hasParameter, shellbuff.parameter); 
	}
	else if(!strcmp(shellbuff.command,"clear")){
		error = s_clear(hasParameter, shellbuff.parameter);
	}
	else if(!strcmp(shellbuff.command,"about")){
		error = s_about(hasParameter, shellbuff.parameter);
	}
	else if(!strcmp(shellbuff.command,"time")){
		error = s_time(hasParameter, shellbuff.parameter);
	}
	else if(!strcmp(shellbuff.command,"bkg")){
		error = s_bkg(hasParameter, shellbuff.parameter);
	}
	else if(!strcmp(shellbuff.command,"ssavercolor")){
		error = s_ssavercolor(hasParameter, shellbuff.parameter);
	}
	else if(!strcmp(shellbuff.command,"ssavertime")){
		error = s_ssavertime(hasParameter, shellbuff.parameter);
	}
	else if(!strcmp(shellbuff.command,"timestyle")){
		error = s_timestyle(hasParameter, shellbuff.parameter);
	}
	else {
		printerror("COMMAND NOT FOUND\n");
	}
	// Print error messages if needed
	switch(error){
		case 1:
			printwarning("Too many arguments.\n");
			break;
		case 2:
			printwarning("Too few arguments.\n");
			break;
		case 3:
			printwarning("Invalid argument.\n");
			break;
		case 4:
			printwarning("This command doesn't receive parameters.\n");
			break;
		default:
			break;
	}
	return;
}