Пример #1
0
int main(int argc, char **argv)
{
    const char * rilLibPath = NULL;
    char **rilArgv;
    void *dlHandle;
    const RIL_RadioFunctions *(*rilInit)(const struct RIL_Env *, int, char **);
    const RIL_RadioFunctions *funcs;
    char libPath[PROPERTY_VALUE_MAX];
    unsigned char hasLibArgs = 0;

    int i;

    umask(S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH);
    for (i = 1; i < argc ;) {
        if (0 == strcmp(argv[i], "-l") && (argc - i > 1)) {
            rilLibPath = argv[i + 1];
            i += 2;
        } else if (0 == strcmp(argv[i], "--")) {
            i++;
            hasLibArgs = 1;
            break;
        } else {
            usage(argv[0]);
        }
    }

    if (rilLibPath == NULL) {
        if ( 0 == property_get(LIB_PATH_PROPERTY, libPath, NULL)) {
            // No lib sepcified on the command line, and nothing set in props.
            // Assume "no-ril" case.
            goto done;
        } else {
            rilLibPath = libPath;
        }
    }

    /* special override when in the emulator */
#if 1
    {
        static char*  arg_overrides[3];
        static char   arg_device[32];
        int           done = 0;

#define  REFERENCE_RIL_PATH  "/system/lib/libreference-ril.so"

        /* first, read /proc/cmdline into memory */
        char          buffer[1024], *p, *q;
        int           len;
        int           fd = open("/proc/cmdline",O_RDONLY);

        if (fd < 0) {
            LOGD("could not open /proc/cmdline:%s", strerror(errno));
            goto OpenLib;
        }

        do {
            len = read(fd,buffer,sizeof(buffer)); }
        while (len == -1 && errno == EINTR);

        if (len < 0) {
            LOGD("could not read /proc/cmdline:%s", strerror(errno));
            close(fd);
            goto OpenLib;
        }
        close(fd);

        if (strstr(buffer, "android.qemud=") != NULL)
        {
            /* the qemud daemon is launched after rild, so
            * give it some time to create its GSM socket
            */
            int  tries = 5;
#define  QEMUD_SOCKET_NAME    "qemud"

            while (1) {
                int  fd;

                sleep(1);

                fd = socket_local_client(
                            QEMUD_SOCKET_NAME,
                            ANDROID_SOCKET_NAMESPACE_RESERVED,
                            SOCK_STREAM );

                if (fd >= 0) {
                    close(fd);
                    snprintf( arg_device, sizeof(arg_device), "%s/%s",
                                ANDROID_SOCKET_DIR, QEMUD_SOCKET_NAME );

                    arg_overrides[1] = "-s";
                    arg_overrides[2] = arg_device;
                    done = 1;
                    break;
                }
                LOGD("could not connect to %s socket: %s",
                    QEMUD_SOCKET_NAME, strerror(errno));
                if (--tries == 0)
                    break;
            }
            if (!done) {
                LOGE("could not connect to %s socket (giving up): %s",
                    QEMUD_SOCKET_NAME, strerror(errno));
                while(1)
                    sleep(0x00ffffff);
            }
        }

        /* otherwise, try to see if we passed a device name from the kernel */
        if (!done) do {
#define  KERNEL_OPTION  "android.ril="
#define  DEV_PREFIX     "/dev/"

            p = strstr( buffer, KERNEL_OPTION );
            if (p == NULL)
                break;

            p += sizeof(KERNEL_OPTION)-1;
            q  = strpbrk( p, " \t\n\r" );
            if (q != NULL)
                *q = 0;

            snprintf( arg_device, sizeof(arg_device), DEV_PREFIX "%s", p );
            arg_device[sizeof(arg_device)-1] = 0;
            arg_overrides[1] = "-d";
            arg_overrides[2] = arg_device;
            done = 1;

        } while (0);

        if (done) {
            argv = arg_overrides;
            argc = 3;
            i    = 1;
            hasLibArgs = 1;
            rilLibPath = REFERENCE_RIL_PATH;

            LOGD("overriding with %s %s", arg_overrides[1], arg_overrides[2]);
        }
    }
OpenLib:
#endif
//    switchUser();

    dlHandle = dlopen(rilLibPath, RTLD_NOW);

    if (dlHandle == NULL) {
        fprintf(stderr, "dlopen failed: %s\n", dlerror());
        exit(-1);
    }

    RIL_startEventLoop();

    rilInit = (const RIL_RadioFunctions *(*)(const struct RIL_Env *, int, char **))dlsym(dlHandle, "RIL_Init");

    if (rilInit == NULL) {
        fprintf(stderr, "RIL_Init not defined or exported in %s\n", rilLibPath);
        exit(-1);
    }

    if (hasLibArgs) {
        rilArgv = argv + i - 1;
        argc = argc -i + 1;
    } else {
        static char * newArgv[MAX_LIB_ARGS];
        static char args[PROPERTY_VALUE_MAX];
        rilArgv = newArgv;
        property_get(LIB_ARGS_PROPERTY, args, "");
        argc = make_argv(args, rilArgv);
    }

    // Make sure there's a reasonable argv[0]
    rilArgv[0] = argv[0];

    funcs = rilInit(&s_rilEnv, argc, rilArgv);

    RIL_register(funcs);

done:

    while(1) {
        // sleep(UINT32_MAX) seems to return immediately on bionic
        sleep(0x00ffffff);
    }
}
Пример #2
0
bool cMobSpawner::CanSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, eMonsterType a_MobType, EMCSBiome a_Biome)
{
	cFastRandom Random;
	BLOCKTYPE TargetBlock = E_BLOCK_AIR;
	if (a_Chunk->UnboundedRelGetBlockType(a_RelX, a_RelY, a_RelZ, TargetBlock))
	{
		if ((a_RelY + 1 > cChunkDef::Height) || (a_RelY - 1 < 0))
		{
			return false;
		}

		NIBBLETYPE BlockLight = a_Chunk->GetBlockLight(a_RelX, a_RelY, a_RelZ);
		NIBBLETYPE SkyLight = a_Chunk->GetSkyLight(a_RelX, a_RelY, a_RelZ);
		BLOCKTYPE BlockAbove = a_Chunk->GetBlock(a_RelX, a_RelY + 1, a_RelZ);
		BLOCKTYPE BlockBelow = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ);

		SkyLight = a_Chunk->GetTimeAlteredLight(SkyLight);

		switch (a_MobType)
		{
			case mtSquid:
			{
				return IsBlockWater(TargetBlock) && (a_RelY >= 45) && (a_RelY <= 62);
			}

			case mtBat:
			{
				return (a_RelY <= 63) && (BlockLight <= 4) && (SkyLight <= 4) && (TargetBlock == E_BLOCK_AIR) && !cBlockInfo::IsTransparent(BlockAbove);
			}

			case mtChicken:
			case mtCow:
			case mtPig:
			case mtHorse:
			case mtSheep:
			{
				return (
					(TargetBlock == E_BLOCK_AIR) &&
					(BlockAbove == E_BLOCK_AIR) &&
					(!cBlockInfo::IsTransparent(BlockBelow)) &&
					(BlockBelow == E_BLOCK_GRASS) &&
					(SkyLight >= 9)
				);
			}
				
			case mtOcelot:
			{
				return (
					(TargetBlock == E_BLOCK_AIR) &&
					(BlockAbove == E_BLOCK_AIR) &&
					(
						(BlockBelow == E_BLOCK_GRASS) || (BlockBelow == E_BLOCK_LEAVES) || (BlockBelow == E_BLOCK_NEW_LEAVES)
					) &&
					(a_RelY >= 62) &&
					(Random.NextInt(3, a_Biome) != 0)
				);
			}
			
			case mtEnderman:
			{
				if (a_RelY < 250)
				{
					BLOCKTYPE BlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 2, a_RelZ);
					if (BlockTop == E_BLOCK_AIR)
					{
						BlockTop = a_Chunk->GetBlock(a_RelX, a_RelY + 3, a_RelZ);
						return (
							(TargetBlock == E_BLOCK_AIR) &&
							(BlockAbove == E_BLOCK_AIR) &&
							(BlockTop == E_BLOCK_AIR) &&
							(!cBlockInfo::IsTransparent(BlockBelow)) &&
							(SkyLight <= 7) &&
							(BlockLight <= 7)
						);
					}
				}
				break;
			}
			
			case mtSpider:
			{
				bool CanSpawn = true;
				bool HasFloor = false;
				for (int x = 0; x < 2; ++x)
				{
					for (int z = 0; z < 2; ++z)
					{
						CanSpawn = a_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY, a_RelZ + z, TargetBlock);
						CanSpawn = CanSpawn && (TargetBlock == E_BLOCK_AIR);
						if (!CanSpawn)
						{
							return false;
						}
						HasFloor = (
							HasFloor ||
							(
								a_Chunk->UnboundedRelGetBlockType(a_RelX + x, a_RelY - 1, a_RelZ + z, TargetBlock) &&
								!cBlockInfo::IsTransparent(TargetBlock)
							)
						);
					}
				}
				return CanSpawn && HasFloor && (SkyLight <= 7) && (BlockLight <= 7);
			}
			
			case mtCreeper:
			case mtSkeleton:
			case mtZombie:
			{
				return (
					(TargetBlock == E_BLOCK_AIR) &&
					(BlockAbove == E_BLOCK_AIR) &&
					(!cBlockInfo::IsTransparent(BlockBelow)) &&
					(SkyLight <= 7) &&
					(BlockLight <= 7) &&
					(Random.NextInt(2, a_Biome) == 0)
				);
			}

			case mtMagmaCube:
			case mtSlime:
			{
				return (
					(TargetBlock == E_BLOCK_AIR) &&
					(BlockAbove == E_BLOCK_AIR) &&
					(!cBlockInfo::IsTransparent(BlockBelow)) &&
					(
						(a_RelY <= 40) || (a_Biome == biSwampland)
					)
				);
			}
			
			case mtGhast:
			case mtZombiePigman:
			{
				return (
					(TargetBlock == E_BLOCK_AIR) &&
					(BlockAbove == E_BLOCK_AIR) &&
					(!cBlockInfo::IsTransparent(BlockBelow)) &&
					(Random.NextInt(20, a_Biome) == 0)
				);
			}
			
			case mtWolf:
			{
				return (
					(TargetBlock == E_BLOCK_GRASS) &&
					(BlockAbove == E_BLOCK_AIR) &&
					(
						(a_Biome == biTaiga) ||
						(a_Biome == biTaigaHills) ||
						(a_Biome == biForest) ||
						(a_Biome == biForestHills) ||
						(a_Biome == biColdTaiga) ||
						(a_Biome == biColdTaigaHills) ||
						(a_Biome == biTaigaM) ||
						(a_Biome == biMegaTaiga) ||
						(a_Biome == biMegaTaigaHills)
					)
				);
			}

			case mtMooshroom:
			{
				return (
					(TargetBlock == E_BLOCK_AIR) &&
					(BlockAbove == E_BLOCK_AIR) &&
					(BlockBelow == E_BLOCK_MYCELIUM) &&
					(
						(a_Biome == biMushroomShore) ||
						(a_Biome == biMushroomIsland)
					)
				);
			}
			
			default:
			{
				LOGD("MG TODO: Write spawning rule for mob type %d", a_MobType);
				return false;
			}
		}
	}
	return false;
}
int zipalign(const char *apk_path, uid_t uid, int is_public)
{
    char za_path[PKG_PATH_MAX];
    struct utimbuf ut;
    struct stat za_stat, apk_stat;
    int res;
    pid_t pid;
    pid = fork();
    if (pid == 0) {
        run_check_zipalign(apk_path);
        exit(67);
    } else {
        res = wait_check_zipalign(pid, apk_path);
        if (res == 0) {
            goto notneeded;
        }
    }    
    
    memset(&apk_stat, 0, sizeof(apk_stat));
    stat(apk_path, &apk_stat);

    strcpy(za_path, apk_path);
    strcat(za_path, ".tmp");
    LOGD("ZipAlign: --- BEGIN '%s' ---\n", apk_path);
    
    pid = fork();
    if (pid == 0) {
        run_zipalign(apk_path, za_path);
        exit(67);
    } else {
        res = wait_zipalign(pid, za_path);
        if (res != 0) {
            LOGE("zipalign failed on '%s' res = %d\n", za_path, res);
            goto fail;
        }
   }
    
    if (chown(za_path, apk_stat.st_uid, apk_stat.st_gid) < 0) {
        LOGE("zipalign cannot chown '%s'", apk_path);
        goto fail;
    }
    if (chmod(za_path, S_IRUSR|S_IWUSR|S_IRGRP |
        (is_public ? S_IROTH : 0)) < 0) {
LOGE("zipalign cannot chmod '%s'\n", apk_path);
goto fail;
    }

    ut.actime = apk_stat.st_atime;
    ut.modtime = apk_stat.st_mtime;
    utime(za_path, &ut);

    unlink(apk_path);
    rename(za_path, apk_path);

    return 0;
    
notneeded:
    return 0;
    
fail:
    unlink(za_path);
    return -1;

}
Пример #4
0
bool
HwcComposer2D::TryHwComposition()
{
    FramebufferSurface* fbsurface = (FramebufferSurface*)(GetGonkDisplay()->GetFBSurface());

    if (!(fbsurface && fbsurface->lastHandle)) {
        LOGD("H/W Composition failed. FBSurface not initialized.");
        return false;
    }

    // Add FB layer
    int idx = mList->numHwLayers++;
    if (idx >= mMaxLayerCount) {
        if (!ReallocLayerList() || idx >= mMaxLayerCount) {
            LOGE("TryHwComposition failed! Could not add FB layer");
            return false;
        }
    }

    Prepare(fbsurface->lastHandle, -1);

    /* Possible composition paths, after hwc prepare:
    1. GPU Composition
    2. BLIT Composition
    3. Full OVERLAY Composition
    4. Partial OVERLAY Composition (GPU + OVERLAY) */

    bool gpuComposite = false;
    bool blitComposite = false;
    bool overlayComposite = true;

    for (int j=0; j < idx; j++) {
        if (mList->hwLayers[j].compositionType == HWC_FRAMEBUFFER ||
            mList->hwLayers[j].compositionType == HWC_BLIT) {
            // Full OVERLAY composition is not possible on this frame
            // It is either GPU / BLIT / partial OVERLAY composition.
            overlayComposite = false;
            break;
        }
    }

    if (!overlayComposite) {
        for (int k=0; k < idx; k++) {
            switch (mList->hwLayers[k].compositionType) {
                case HWC_FRAMEBUFFER:
                    gpuComposite = true;
                    break;
                case HWC_BLIT:
                    blitComposite = true;
                    break;
                case HWC_OVERLAY:
                    // HWC will compose HWC_OVERLAY layers in partial
                    // Overlay Composition, set layer composition flag
                    // on mapped LayerComposite to skip GPU composition
                    mHwcLayerMap[k]->SetLayerComposited(true);
                    if ((mList->hwLayers[k].hints & HWC_HINT_CLEAR_FB) &&
                        (mList->hwLayers[k].blending == HWC_BLENDING_NONE)) {
                        // Clear visible rect on FB with transparent pixels.
                        hwc_rect_t r = mList->hwLayers[k].displayFrame;
                        mHwcLayerMap[k]->SetClearRect(nsIntRect(r.left, r.top,
                                                                r.right - r.left,
                                                                r.bottom - r.top));
                    }
                    break;
                default:
                    break;
            }
        }

        if (gpuComposite) {
            // GPU or partial OVERLAY Composition
            return false;
        } else if (blitComposite) {
            // Some EGLSurface implementations require glClear() on blit composition.
            // See bug 1029856.
            if (mGLContext) {
                mGLContext->MakeCurrent();
                mGLContext->fClearColor(0.0, 0.0, 0.0, 0.0);
                mGLContext->fClear(LOCAL_GL_COLOR_BUFFER_BIT);
            }
            // BLIT Composition, flip FB target
            GetGonkDisplay()->UpdateFBSurface(mDpy, mSur);
            FramebufferSurface* fbsurface = (FramebufferSurface*)(GetGonkDisplay()->GetFBSurface());
            if (!fbsurface) {
                LOGE("H/W Composition failed. NULL FBSurface.");
                return false;
            }
            mList->hwLayers[idx].handle = fbsurface->lastHandle;
            mList->hwLayers[idx].acquireFenceFd = fbsurface->GetPrevFBAcquireFd();
        }
    }

    // BLIT or full OVERLAY Composition
    Commit();

    GetGonkDisplay()->SetFBReleaseFd(mList->hwLayers[idx].releaseFenceFd);
    mList->hwLayers[idx].releaseFenceFd = -1;
    return true;
}
Пример #5
0
static bool client_connection(int fd)
{
    bool ret = true;
    auto fail = util::finally([&] {
        if (!ret) {
            LOGE("Killing connection");
        }
    });

    LOGD("Accepted connection from %d", fd);

    struct ucred cred;
    socklen_t cred_len = sizeof(struct ucred);

    if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &cred_len) < 0) {
        LOGE("Failed to get socket credentials: %s", strerror(errno));
        return ret = false;
    }

    LOGD("Client PID: %u", cred.pid);
    LOGD("Client UID: %u", cred.uid);
    LOGD("Client GID: %u", cred.gid);

    if (verify_credentials(cred.uid)) {
        if (!util::socket_write_string(fd, RESPONSE_ALLOW)) {
            LOGE("Failed to send credentials allowed message");
            return ret = false;
        }
    } else {
        if (!util::socket_write_string(fd, RESPONSE_DENY)) {
            LOGE("Failed to send credentials denied message");
        }
        return ret = false;
    }

    int32_t version;
    if (!util::socket_read_int32(fd, &version)) {
        LOGE("Failed to get interface version");
        return ret = false;
    }

    if (version == 2) {
        LOGE("Protocol version 2 is no longer supported");
        util::socket_write_string(fd, RESPONSE_UNSUPPORTED);
        return ret = false;
    } else if (version == 3) {
        if (!util::socket_write_string(fd, RESPONSE_OK)) {
            return false;
        }

        if (!connection_version_3(fd)) {
            LOGE("[Version 3] Communication error");
        }
        return true;
    } else {
        LOGE("Unsupported interface version: %d", version);
        util::socket_write_string(fd, RESPONSE_UNSUPPORTED);
        return ret = false;
    }

    return true;
}
Пример #6
0
static void replace_method (Package *pkg) {
    xmono::ReplaceMethodReq req;
    xmono::ReplaceMethodRsp rsp;
    std::string str((char*)pkg->body, pkg->all_len - sizeof (Package));
    if (!req.ParseFromString (str)) {
        LOGD ("xmono::ReplaceMethodReq ParseFromString err!");
        return;
    }
    std::string err;
    void *p, *old_p;
    uint8_t *code;
    int code_size;
    MonoMethodHeader *mh;
    MonoThread *thread;
    MonoMethod *new_method;
    MonoDomain *domain;
    MonoMethod * method = get_method_with_token (req.image_name ().c_str (), req.method_token ());
    if (!method) {
        rsp.set_err (false);
        rsp.set_msg (helper_last_err ());
        goto replace_method_end;
    }
    domain = mono_domain_get_by_id (req.domain_id ());
    if (!domain) {
        rsp.set_err (false);
        rsp.set_msg ("can not get the domain from id");
        goto replace_method_end;
    }
    mh = mono_method_get_header (method);
    if (req.ex_size () != mono_method_header_get_num_clauses (mh)) {
        rsp.set_err (false);
        rsp.set_msg ("ex size != mono_method_header_clauses size!");
        goto replace_method_end;
    }
    for (int i = 0; i < req.ex_size (); i++) {
        xmono::ReplaceMethodReq_ExceptionClause const &e = req.ex (i);
        void *iter = 0;
        MonoExceptionClause *clauses = &mh->clauses[i];
        MonoExceptionClause *old_e = (MonoExceptionClause*)iter;
        old_e->try_offset = e.try_offset ();
        old_e->try_len = e.try_len ();
        old_e->handler_offset = e.handler_offset ();
        old_e->handler_len = e.handler_len ();
    }
    code = new uint8_t[req.new_code ().size ()];
    memcpy (code, req.new_code ().c_str (), req.new_code ().size ());
    mh->code = code;
    mh->code_size = req.new_code ().size ();
    thread = mono_thread_attach (domain);
    /*128 是一个估计值, 在未来可能不稳定, 但当前只能如此*/
    new_method = (MonoMethod*)calloc (128, 1); /*这个地方用malloc优于用new*/
    memcpy (new_method, method, 128);

    pthread_mutex_lock (&replace_mutex);
    replace_method_dict[new_method] = true;
    pthread_mutex_unlock (&replace_mutex);

    p = mono_compile_method (new_method);
    memcpy (hooked_method_dict[method]->specific_hook + 4, &p, 4);

    pthread_mutex_lock (&hooked_mutex);
    old_p = mono_jit_info_get_code_start (hooked_method_dict[method]->jinfo);
    pthread_mutex_unlock (&hooked_mutex);

    mono_thread_detach (thread);
    LOGD ("compile method, new ptr : %p, old ptr : %p", p, old_p);
    rsp.set_err (true);
    rsp.set_msg ("replace_method successful.");
replace_method_end:
    std::string out;
    rsp.SerializeToString (&out);
    ecmd_send (XMONO_ID_REPLACE_METHOD_RSP, (uint8_t const*)out.c_str (), out.size ());
    return;
}
Пример #7
0
extern "C" int so_main() {
    LOGD ("hello, xmono");
    install_jit_profile ();
    init_network ();
    return 0;
}
Пример #8
0
Application::~Application()
{
	LOGD("Application::Destructor()");

     destroy();
}
Пример #9
0
bool StyleContext::evalStyle(FunctionID _id, StyleParamKey _key, StyleParam::Value& _val) {
    _val = none_type{};

    JSScope jsScope(*m_jsContext);
    auto jsValue = jsScope.getFunctionResult(_id);
    if (!jsValue) {
        return false;
    }

    if (jsValue.isString()) {
        std::string value = jsValue.toString();

        switch (_key) {
            case StyleParamKey::outline_style:
            case StyleParamKey::repeat_group:
            case StyleParamKey::sprite:
            case StyleParamKey::sprite_default:
            case StyleParamKey::style:
            case StyleParamKey::text_align:
            case StyleParamKey::text_repeat_group:
            case StyleParamKey::text_source:
            case StyleParamKey::text_source_left:
            case StyleParamKey::text_source_right:
            case StyleParamKey::text_transform:
            case StyleParamKey::texture:
                _val = value;
                break;
            case StyleParamKey::color:
            case StyleParamKey::outline_color:
            case StyleParamKey::text_font_fill:
            case StyleParamKey::text_font_stroke_color: {
                Color result;
                if (StyleParam::parseColor(value, result)) {
                    _val = result.abgr;
                } else {
                    LOGW("Invalid color value: %s", value.c_str());
                }
                break;
            }
            default:
                _val = StyleParam::parseString(_key, value);
                break;
        }

    } else if (jsValue.isBoolean()) {
        bool value = jsValue.toBool();

        switch (_key) {
            case StyleParamKey::interactive:
            case StyleParamKey::text_interactive:
            case StyleParamKey::visible:
                _val = value;
                break;
            case StyleParamKey::extrude:
                _val = value ? glm::vec2(NAN, NAN) : glm::vec2(0.0f, 0.0f);
                break;
            default:
                break;
        }

    } else if (jsValue.isArray()) {
        auto len = jsValue.getLength();

        switch (_key) {
            case StyleParamKey::extrude: {
                if (len != 2) {
                    LOGW("Wrong array size for extrusion: '%d'.", len);
                    break;
                }

                double v1 = jsValue.getValueAtIndex(0).toDouble();
                double v2 = jsValue.getValueAtIndex(1).toDouble();

                _val = glm::vec2(v1, v2);
                break;
            }
            case StyleParamKey::color:
            case StyleParamKey::outline_color:
            case StyleParamKey::text_font_fill:
            case StyleParamKey::text_font_stroke_color: {
                if (len < 3 || len > 4) {
                    LOGW("Wrong array size for color: '%d'.", len);
                    break;
                }
                double r = jsValue.getValueAtIndex(0).toDouble();
                double g = jsValue.getValueAtIndex(1).toDouble();
                double b = jsValue.getValueAtIndex(2).toDouble();
                double a = 1.0;
                if (len == 4) {
                    a = jsValue.getValueAtIndex(3).toDouble();
                }
                _val = ColorF(r, g, b, a).toColor().abgr;
                break;
            }
            default:
                break;
        }
    } else if (jsValue.isNumber()) {
        double number = jsValue.toDouble();
        if (std::isnan(number)) {
            LOGD("duk evaluates JS method to NAN.\n");
        }
        switch (_key) {
            case StyleParamKey::text_source:
            case StyleParamKey::text_source_left:
            case StyleParamKey::text_source_right:
                _val = doubleToString(number);
                break;
            case StyleParamKey::extrude:
                _val = glm::vec2(0.f, number);
                break;
            case StyleParamKey::placement_spacing: {
                _val = StyleParam::Width{static_cast<float>(number), Unit::pixel};
                break;
            }
            case StyleParamKey::width:
            case StyleParamKey::outline_width: {
                // TODO more efficient way to return pixels.
                // atm this only works by return value as string
                _val = StyleParam::Width{static_cast<float>(number)};
                break;
            }
            case StyleParamKey::angle:
            case StyleParamKey::priority:
            case StyleParamKey::text_priority:
            case StyleParamKey::text_font_stroke_width:
            case StyleParamKey::placement_min_length_ratio: {
                _val = static_cast<float>(number);
                break;
            }
            case StyleParamKey::size: {
                StyleParam::SizeValue vec;
                vec.x.value = static_cast<float>(number);
                _val = vec;
                break;
            }
            case StyleParamKey::order:
            case StyleParamKey::outline_order:
            case StyleParamKey::color:
            case StyleParamKey::outline_color:
            case StyleParamKey::text_font_fill:
            case StyleParamKey::text_font_stroke_color: {
                _val = static_cast<uint32_t>(number);
                break;
            }
            default:
                break;
        }
    } else if (jsValue.isUndefined()) {
        // Explicitly set value as 'undefined'. This is important for some styling rules.
        _val = Undefined();
    } else {
        LOGW("Unhandled return type from Javascript style function for %d.", _key);
    }

    return !_val.is<none_type>();
}
Пример #10
0
int Application::init(JNIEnv *env, const char * apkAbsolutePath)
{
     LOGD("APK_PATH: %s", apkAbsolutePath);

     // TODO: setup genesis directories

     // copy dirs for storage
     if (apkAbsolutePath == NULL || strlen(apkAbsolutePath) >= MAX_PATH)
     {
    	 return NATIVE_ERROR;
     }

     strcpy(_apkPath, apkAbsolutePath);

     if (!_fceuInitialized)
     {
    	 // allocate cart
    	 cart.rom = (unsigned char*)memalign(32, MAXROMSIZE);

    	 // load bios
    	 //load_bios();

    	 /* allocate global work bitmap */
    	 memset (&bitmap, 0, sizeof (bitmap));
    	 bitmap.width  = GENPLUS_RENDER_TEXTURE_WIDTH;
    	 bitmap.height = GENPLUS_RENDER_TEXTURE_HEIGHT;
    	 bitmap.depth  = 16;
    	 bitmap.granularity = SCREEN_RENDER_BYTE_BY_PIXEL;
    	 bitmap.pitch = bitmap.width * bitmap.granularity;
    	 bitmap.viewport.w = GENPLUS_RENDER_TEXTURE_WIDTH;
    	 bitmap.viewport.h = GENPLUS_RENDER_TEXTURE_HEIGHT;
    	 bitmap.viewport.x = 0;
    	 bitmap.viewport.y = 0;
    	 bitmap.remap = 1;
    	 bitmap.data = (unsigned char*)malloc(bitmap.width*bitmap.height*bitmap.granularity);

    	 // version TAG
    	 strncpy(config.version,CONFIG_VERSION,16);

    	 // sound options
    	 config.psg_preamp     = 150;
    	 config.fm_preamp      = 100;
    	 config.hq_fm          = 1;
    	 config.psgBoostNoise  = 0;
    	 config.filter         = 1;
    	 config.lp_range       = 50;
    	 config.low_freq       = 880;
    	 config.high_freq      = 5000;
    	 config.lg             = 1.0;
    	 config.mg             = 1.0;
    	 config.hg             = 1.0;
    	 config.rolloff        = 0.995;
    	 config.dac_bits       = 14;

    	 // system options
    	 config.region_detect  = 0;
    	 config.force_dtack    = 0;
    	 config.addr_error     = 0;
    	 config.tmss           = 0;
    	 config.lock_on        = 0;//Settings.ExtraCart;
    	 config.romtype        = 0;
    	 config.hot_swap       = 0;

    	 // video options
    	 config.xshift   = 0;
    	 config.yshift   = 0;
    	 config.xscale   = 0;
    	 config.yscale   = 0;
    	 config.aspect   = 0; // 1 for 4:3, 2 for 16:9
    	 config.overscan = 0;

    	 _fceuInitialized = true;
     }

     _initialized = true;

     return NATIVE_OK;
}
Пример #11
0
int Application::loadROM(const char* filename)
{
	LOGD("NDK:LoadingRom: %s", filename);

	if (_romLoaded)
	{
		// TODO: close genesis

		// save sram
		saveSRam(_sramDir);

		_romLoaded = false;
	}

     /* load ROM file */
   	if (!load_rom((char*)filename))
   	{
   		LOGD("Error loading rom!");
   		return NATIVE_ERROR;
   	}

   	// store current rom
   	strcpy(_currentRom, filename);

   	// controllers options
	config.gun_cursor[0]  = 1;
	config.gun_cursor[1]  = 1;
	config.invert_mouse   = 0;
	config.s_device = 0;

	LOGD("GenesisPlus Hardware: %d", system_hw);

	if (system_hw == SYSTEM_MEGADRIVE || system_hw == SYSTEM_GENESIS)
	{
		Input.setButtonVisibility(BUTTON_INDEX_C, true);
		Input.setButtonVisibility(BUTTON_INDEX_X, true);
		Input.setButtonVisibility(BUTTON_INDEX_Y, true);
		Input.setButtonVisibility(BUTTON_INDEX_Z, true);

		input.system[0]       = SYSTEM_MD_GAMEPAD;
		input.system[1]       = SYSTEM_MD_GAMEPAD;

		config.input[0].padtype = DEVICE_PAD6B;
	}
	else if (system_hw == SYSTEM_PBC)
	{
		Input.setButtonVisibility(BUTTON_INDEX_C, false);
		Input.setButtonVisibility(BUTTON_INDEX_X, false);
		Input.setButtonVisibility(BUTTON_INDEX_Y, false);
		Input.setButtonVisibility(BUTTON_INDEX_Z, false);

		input.system[0]       = SYSTEM_MS_GAMEPAD;
		input.system[1]       = SYSTEM_MS_GAMEPAD;
		config.input[0].padtype = DEVICE_PAD2B;
	}

	input_init();

    // hot-swap previous & current cartridge
   	bool hotswap = config.hot_swap && cart.romsize;
   	//cart.romsize = size;

   	if(hotswap)
	{
   		if (system_hw == SYSTEM_PBC)
   		{
   			sms_cart_init();
   			sms_cart_reset();
   		}
   		else
   		{
   			md_cart_init();
   			md_cart_reset(1);
   		}
	}
   	else
   	{
   		// initialize audio emulation
   		audio_init(_sampleRate, vdp_pal ? 50.0 : 60.0);

   		// system power ON
   		system_init();
   		system_reset();
   	}

   	// sram
   	loadSRam(_currentRom);

   	// mark video updated
   	bitmap.viewport.changed |= 1;

     /* load Cheats */
     //CheatLoad();

   	_ssize = 0;

    _romLoaded = true;

     return NATIVE_OK;
}
Пример #12
0
/*
 * Magic "internal native" code stub, inserted into abstract method
 * definitions when a class is first loaded.  This throws the expected
 * exception so we don't have to explicitly check for it in the interpreter.
 */
void dvmAbstractMethodStub(const u4* args, JValue* pResult)
{
    LOGD("--- called into dvmAbstractMethodStub\n");
    dvmThrowException("Ljava/lang/AbstractMethodError;",
        "abstract method not implemented");
}
Пример #13
0
void  AT_DUMP(const char*  prefix, const char*  buff, int  len)
{
    if (len < 0)
        len = strlen(buff);
    LOGD("%.*s", len, buff);
}
Пример #14
0
static const char *readline()
{
    ssize_t count;

    char *p_read = NULL;
    char *p_eol = NULL;
    char *ret;

    /* this is a little odd. I use *s_ATBufferCur == 0 to
     * mean "buffer consumed completely". If it points to a character, than
     * the buffer continues until a \0
     */
    if (*s_ATBufferCur == '\0') {
        /* empty buffer */
        s_ATBufferCur = s_ATBuffer;
        *s_ATBufferCur = '\0';
        p_read = s_ATBuffer;
    } else {   /* *s_ATBufferCur != '\0' */
        /* there's data in the buffer from the last read */

        // skip over leading newlines
        while (*s_ATBufferCur == '\r' || *s_ATBufferCur == '\n')
            s_ATBufferCur++;

        p_eol = findNextEOL(s_ATBufferCur);

        if (p_eol == NULL) {
            /* a partial line. move it up and prepare to read more */
            size_t len;

            len = strlen(s_ATBufferCur);

            memmove(s_ATBuffer, s_ATBufferCur, len + 1);
            p_read = s_ATBuffer + len;
            s_ATBufferCur = s_ATBuffer;
        }
        /* Otherwise, (p_eol !- NULL) there is a complete line  */
        /* that will be returned the while () loop below        */
    }

    while (p_eol == NULL) {
        if (0 == MAX_AT_RESPONSE - (p_read - s_ATBuffer)) {
            LOGE("ERROR: Input line exceeded buffer\n");
            /* ditch buffer and start over again */
            s_ATBufferCur = s_ATBuffer;
            *s_ATBufferCur = '\0';
            p_read = s_ATBuffer;
        }

        do {
            count = read(s_fd, p_read,
                            MAX_AT_RESPONSE - (p_read - s_ATBuffer));
        } while (count < 0 && errno == EINTR);

        if (count > 0) {
            AT_DUMP( "<< ", p_read, count );
            s_readCount += count;

            p_read[count] = '\0';

            // skip over leading newlines
            while (*s_ATBufferCur == '\r' || *s_ATBufferCur == '\n')
                s_ATBufferCur++;

            p_eol = findNextEOL(s_ATBufferCur);
            p_read += count;
        } else if (count <= 0) {
            /* read error encountered or EOF reached */
            if(count == 0) {
                LOGD("atchannel: EOF reached");
            } else {
                LOGD("atchannel: read error %s", strerror(errno));
            }
            return NULL;
        }
    }

    /* a full line in the buffer. Place a \0 over the \r and return */

    ret = s_ATBufferCur;
    *p_eol = '\0';
    s_ATBufferCur = p_eol + 1; /* this will always be <= p_read,    */
                              /* and there will be a \0 at *p_read */

    LOGD("AT< %s\n", ret);
    return ret;
}
Пример #15
0
int predict(float **values, int **indices, int rowNum, int colNum, int isProb,
        const char *modelFile, int *labels, double* prob_estimates) {
    LOGD("Coming into classification\n");
    return svmpredict(values, indices, rowNum, colNum, isProb, modelFile, labels, prob_estimates);
}
Пример #16
0
bool defaultEGLChooser(EGLDisplay disp, EGLConfig& bestConfig)
{

	EGLint count = 0;
	if (!eglGetConfigs(disp, NULL, 0, &count))
	{
		LOGE("defaultEGLChooser cannot query count of all configs");
		return false;
	}

	LOGD("Config count = %d", count);

	EGLConfig* configs = new EGLConfig[count];
	if (!eglGetConfigs(disp, configs, count, &count))
	{
		LOGE("defaultEGLChooser cannot query all configs");
		return false;
	}

	int bestMatch = 1<<30;
	int bestIndex = -1;

	int i;
	for (i = 0; i < count; i++)
	{
		int match = 0;
		EGLint surfaceType = 0;
		EGLint blueBits = 0;
		EGLint greenBits = 0;
		EGLint redBits = 0;
		EGLint alphaBits = 0;
		EGLint depthBits = 0;
		EGLint stencilBits = 0;
		EGLint renderableFlags = 0;

		eglGetConfigAttrib(disp, configs[i], EGL_SURFACE_TYPE, &surfaceType);
		eglGetConfigAttrib(disp, configs[i], EGL_BLUE_SIZE, &blueBits);
		eglGetConfigAttrib(disp, configs[i], EGL_GREEN_SIZE, &greenBits);
		eglGetConfigAttrib(disp, configs[i], EGL_RED_SIZE, &redBits);
		eglGetConfigAttrib(disp, configs[i], EGL_ALPHA_SIZE, &alphaBits);
		eglGetConfigAttrib(disp, configs[i], EGL_DEPTH_SIZE, &depthBits);
		eglGetConfigAttrib(disp, configs[i], EGL_STENCIL_SIZE, &stencilBits);
		eglGetConfigAttrib(disp, configs[i], EGL_RENDERABLE_TYPE, &renderableFlags);
		LOGD("Config[%d]: R%dG%dB%dA%d D%dS%d Type=%04x Render=%04x",
			i, redBits, greenBits, blueBits, alphaBits, depthBits, stencilBits, surfaceType, renderableFlags);

		if ((surfaceType & EGL_WINDOW_BIT) == 0)
			continue;
		if ((renderableFlags & EGL_OPENGL_ES2_BIT) == 0)
			continue;
		if (depthBits < 16)
			continue;
		if ((redBits < 5) || (greenBits < 6) || (blueBits < 5))
			continue;

		int penalty = depthBits - 16;
		match += penalty * penalty;
		penalty = redBits - 5;
		match += penalty * penalty;
		penalty = greenBits - 6;
		match += penalty * penalty;
		penalty = blueBits - 5;
		match += penalty * penalty;
		penalty = alphaBits;
		match += penalty * penalty;
		penalty = stencilBits;
		match += penalty * penalty;

		if ((match < bestMatch) || (bestIndex == -1))
		{
			bestMatch = match;
			bestIndex = i;
			LOGD("Config[%d] is the new best config", i, configs[i]);
		}
	}

	if (bestIndex < 0)
	{
		delete[] configs;
		return false;
	}

	bestConfig = configs[bestIndex];
	delete[] configs;

	return true;
}
Пример #17
0
/*mono正常退出时 该函数被调用*/
static void mono_shutdown (MonoProfiler *prof) {
    LOGD ("mono over.");
}
Пример #18
0
static int fb_open(struct FB *fb)
{
	if (NULL == fb)
	{
		return -1;
	}

	fb->fd = open("/dev/graphics/fb0", O_RDONLY | O_RDWR);
	if (fb->fd < 0)
	{
		printf("open(\"/dev/graphics/fb0\") failed!\n");
		LOGI("---open(\"/dev/graphics/fb0\") failed!---");
		return -1;
	}

	struct fb_var_screeninfo vi;
	vi.xres = 1088;
	vi.yres = 1800;
	vi.xres_virtual = 1088;
	vi.yres_virtual = 4000;

	ioctl(fb->fd, FBIOPUT_VSCREENINFO, vi);


	if (ioctl(fb->fd, FBIOGET_FSCREENINFO, &fb->fi) < 0)
	{
		printf("FBIOGET_FSCREENINFO failed!\n");
		LOGI("---FBIOGET_FSCREENINFO failed!---");
		goto fail;
	}

	LOGD("====== smem_start : %lu",  fb->fi.smem_start);
	// Framebuffer设备的大小
	LOGD("====== smem_len : %d",  fb->fi.smem_len);
	// 一行的byte数目 除以 (bits_per_pixel/8) 就是一行的像素点的数目
	LOGD("====== line_length : %d",  fb->fi.line_length);

	//FB_TYPE_PACKED_PIXELS                0       /* Packed Pixels        */
	//FB_TYPE_PLANES                            1       /* Non interleaved planes */
	//FB_TYPE_INTERLEAVED_PLANES      2       /* Interleaved planes   */
	//FB_TYPE_TEXT                                3       /* Text/attributes      */
	//FB_TYPE_VGA_PLANES                    4       /* EGA/VGA planes       */
	//FB_TYPE_FOURCC                          5       /* Type identified by a V4L2 FOURCC */
	LOGD("====== type : %d",  fb->fi.type);

	if (ioctl(fb->fd, FBIOGET_VSCREENINFO, &fb->vi) < 0)
	{
		printf("FBIOGET_VSCREENINFO failed!\n");
		LOGI("---FBIOGET_VSCREENINFO failed!---");
		goto fail;
	}



	/*打印信息*/
	{
		// 这两个是显示在显示屏上时候的分辨率
		LOGD("====== xres : %d",  fb->vi.xres);
		LOGD("====== yres : %d",  fb->vi.yres);
		// 这两个是显存缓存的分辨率 如果显存缓存了两个屏幕的时候
		// yres_virtula 应该等于 yres * 2
		// 而 xres_virtual 就应该 == xres
		LOGD("====== xres_virtual : %d",  fb->vi.xres_virtual);
		LOGD("====== yres_virtual : %d",  fb->vi.yres_virtual);

		/* offset from virtual to visible */
		// 显存可能缓存了多个屏幕,哪到底哪个屏幕才是显示屏应该显示的内容呢
		// 这就是由下面这两个offset来决定了
		LOGD("====== xoffset : %d",  fb->vi.xoffset);
		LOGD("====== yoffset : %d",  fb->vi.yoffset);

		LOGD("====== bits_per_pixel : %d",  fb->vi.bits_per_pixel);

		// 下面这一段是每个像素点的格式
		LOGD("====== fb_bitfield red.offset : %d",  fb->vi.red.offset);
		LOGD("====== fb_bitfield red.length : %d",  fb->vi.red.length);
		// 如果 == 0,指的是数据的最高有效位在最左边 也就是Big endian
		LOGD("====== fb_bitfield red.msb_right : %d",  fb->vi.red.msb_right);
		LOGD("====== fb_bitfield green.offset : %d",  fb->vi.green.offset);
		LOGD("====== fb_bitfield green.length : %d",  fb->vi.green.length);
		LOGD("====== fb_bitfield green.msb_right : %d",  fb->vi.green.msb_right);
		LOGD("====== fb_bitfield blue.offset : %d",  fb->vi.blue.offset);
		LOGD("====== fb_bitfield blue.length : %d",  fb->vi.blue.length);
		LOGD("====== fb_bitfield blue.msb_right : %d",  fb->vi.blue.msb_right);
		LOGD("====== fb_bitfield transp.offset : %d",  fb->vi.transp.offset);
		LOGD("====== fb_bitfield transp.length : %d",  fb->vi.transp.length);
		LOGD("====== fb_bitfield transp.msb_right : %d",  fb->vi.transp.msb_right);

		LOGD("====== height : %d",  fb->vi.height);
		// width of picture in mm 毫米
		LOGD("====== width : %d",  fb->vi.width);


		LOGD("====== left_margin : %d",  fb->vi.left_margin);
		LOGD("====== right_margin : %d",  fb->vi.right_margin);
		LOGD("====== upper_margin : %d",  fb->vi.upper_margin);
		LOGD("====== lower_margin : %d",  fb->vi.lower_margin);
		LOGD("====== hsync_len : %d",  fb->vi.hsync_len);
		LOGD("====== vsync_len : %d",  fb->vi.vsync_len);
		LOGD("====== sync : %d",  fb->vi.sync);

		LOGD("====== pixclock : %d",  fb->vi.pixclock);
		LOGD("====== accel_flags : %d",  fb->vi.accel_flags);

		// UP 0
		// CW 1
		// UD 2
		// CCW 3
		/* angle we rotate counter clockwise */
		LOGD("====== rotate : %d",  fb->vi.rotate);
	}

	fb->bits = mmap(0, fb_virtual_size(fb), PROT_READ, MAP_SHARED, fb->fd, 0);


	if (fb->bits == MAP_FAILED) {
		printf("mmap() failed!\n");
		LOGI("---mmap()失败!---");
		goto fail;
	}

	return 0;

	fail:
	LOGI("---fb_open()失败!---");
	close(fb->fd);
	return -1;
}
Пример #19
0
static void ecmd_err_callback () {
    LOGD ("ecmd err!");
    exit (1);
}
/*
 * Class:     my_streamplayer_Rtsplayer
 * Method:    CreateRec
 * Signature: (Landroid/graphics/Bitmap;Ljava/lang/String;Ljava/lang/String;IIII)V
 */
void Java_my_streamplayer_Rtsplayer_CreateRec
(JNIEnv *env, jobject, jstring URL, jstring recfile, jint ID, jint x, jint y, jint frame_rate, jobject bitmap)
{
	jboolean isCopy;
	char* rtspURL = (char*) env->GetStringUTFChars(URL, &isCopy);
	char* RecFile = (char*) env->GetStringUTFChars(recfile, &isCopy);
	LOGI("CAM ID %d \tURL: %s \t FILE: %s\n ", ID, rtspURL, RecFile);

	int ret;

	switch(ID)
	{
	case 1:
		if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) {
			LOGI("AndroidBitmap_getInfo() failed ! error=%d", ret);
			return;
		}
		LOGI("Checked on the bitmap 1 ");

		if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixel1)) < 0) {
			LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret);
		}

		MyIPCAM1 = new ipcam_camera(rtspURL, ID, frame_rate);
		MyIPCAM1->init();      // initialize ring buffers
		MyIPCAM1->set_recFile(RecFile);

		//create FFMPEG Decoder - must be getting created here
		videoDecode1 = ipcam_vdec::getInstance(1);
		videoDecode1->setparam(x, y);
		MyIPCAM1->pVDec = videoDecode1;

		usleep (1000);
		//	videoDecode1->InitMPEG4Dec();  //doing this in play now, in playcontinueAfterDESCRIBE

		errorCam1 = MyIPCAM1->play_connect();
		//	MyIPCAM1->rec_connect();

		LOGD("IPCAM %d errorCam1 %d  widthframe : %d, heightframe =%d \n", ID, errorCam1 , x, y);
		break;

	case 2:
		if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) {
			LOGI("AndroidBitmap_getInfo() failed ! error=%d", ret);
			return;
		}
		LOGI("Checked on the bitmap 2");

		if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixel2)) < 0) {
			LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret);
		}

		MyIPCAM2 = new ipcam_camera(rtspURL, ID, frame_rate);
		MyIPCAM2->init();      // initialize ring buffers
		MyIPCAM2->set_recFile(RecFile);

		//create FFMPEG Decoder - must be getting created here
		videoDecode2 = ipcam_vdec::getInstance(2);
		videoDecode2->setparam(x, y);
		MyIPCAM2->pVDec = videoDecode2;
		//now initialize init
		usleep (1000);
		//videoDecode2->InitMPEG4Dec();
		errorCam2 = MyIPCAM2->play_connect();

		LOGD("IPCAM %d errorCam2 %d  widthframe : %d, heightframe =%d \n", ID, errorCam2 , x, y);
		break;

	case 3:
		if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) {
			LOGI("AndroidBitmap_getInfo() failed ! error=%d", ret);
			return;
		}
		LOGI("Checked on the bitmap");

		if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixel3)) < 0) {
			LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret);
		}
		LOGI("Grabbed the pixels");

		MyIPCAM3 = new ipcam_camera(rtspURL, ID, frame_rate);
		MyIPCAM3->init();      // initialize ring buffers
		MyIPCAM3->set_recFile(RecFile);

		//create FFMPEG Decoder - must be getting created here
		videoDecode3 = ipcam_vdec::getInstance(3);
		videoDecode3->setparam(x, y);
		MyIPCAM3->pVDec = videoDecode3;

		usleep (1000);
		//videoDecode3->InitMPEG4Dec();

		errorCam3 = MyIPCAM3->play_connect();
		//	MyIPCAM1->rec_connect();

		LOGD("IPCAM %d errorCam3 %d  widthframe : %d, heightframe =%d \n", ID, errorCam3 , x, y);
		break;

	case 4:
		if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) {
			LOGI("AndroidBitmap_getInfo() failed ! error=%d", ret);
			return;
		}
		LOGI("Checked on the bitmap");

		if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixel4)) < 0) {
			LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret);
		}
		LOGI("Grabbed the pixels");

		MyIPCAM4 = new ipcam_camera(rtspURL, ID, frame_rate);
		MyIPCAM4->init();      // initialize ring buffers
		MyIPCAM4->set_recFile(RecFile);

		//create FFMPEG Decoder - must be getting created here
		videoDecode4 = ipcam_vdec::getInstance(4);
		videoDecode4->setparam(x, y);
		MyIPCAM4->pVDec = videoDecode4;

		usleep (1000);
		//videoDecode4->InitMPEG4Dec();

		errorCam4 = MyIPCAM4->play_connect();
		//	MyIPCAM1->rec_connect();

		LOGD("IPCAM %d errorCam4 %d  widthframe : %d, heightframe =%d \n", ID, errorCam4 , x, y);
		break;

	default:
		LOGE("INVALID CAM-ID %d", ID);
		break;
	}
}
Пример #21
0
bool
HwcComposer2D::PrepareLayerList(Layer* aLayer,
                                const nsIntRect& aClip,
                                const Matrix& aParentTransform)
{
    // NB: we fall off this path whenever there are container layers
    // that require intermediate surfaces.  That means all the
    // GetEffective*() coordinates are relative to the framebuffer.

    bool fillColor = false;

    const nsIntRegion& visibleRegion = aLayer->GetEffectiveVisibleRegion();
    if (visibleRegion.IsEmpty()) {
        return true;
    }

    uint8_t opacity = std::min(0xFF, (int)(aLayer->GetEffectiveOpacity() * 256.0));
#if ANDROID_VERSION < 18
    if (opacity < 0xFF) {
        LOGD("%s Layer has planar semitransparency which is unsupported by hwcomposer", aLayer->Name());
        return false;
    }
#endif

    if (aLayer->GetMaskLayer()) {
      LOGD("%s Layer has MaskLayer which is unsupported by hwcomposer", aLayer->Name());
      return false;
    }

    nsIntRect clip;
    if (!HwcUtils::CalculateClipRect(aParentTransform,
                                     aLayer->GetEffectiveClipRect(),
                                     aClip,
                                     &clip))
    {
        LOGD("%s Clip rect is empty. Skip layer", aLayer->Name());
        return true;
    }

    // HWC supports only the following 2D transformations:
    //
    // Scaling via the sourceCrop and displayFrame in HwcLayer
    // Translation via the sourceCrop and displayFrame in HwcLayer
    // Rotation (in square angles only) via the HWC_TRANSFORM_ROT_* flags
    // Reflection (horizontal and vertical) via the HWC_TRANSFORM_FLIP_* flags
    //
    // A 2D transform with PreservesAxisAlignedRectangles() has all the attributes
    // above
    Matrix layerTransform;
    if (!aLayer->GetEffectiveTransform().Is2D(&layerTransform) ||
        !layerTransform.PreservesAxisAlignedRectangles()) {
        LOGD("Layer EffectiveTransform has a 3D transform or a non-square angle rotation");
        return false;
    }

    Matrix layerBufferTransform;
    if (!aLayer->GetEffectiveTransformForBuffer().Is2D(&layerBufferTransform) ||
        !layerBufferTransform.PreservesAxisAlignedRectangles()) {
        LOGD("Layer EffectiveTransformForBuffer has a 3D transform or a non-square angle rotation");
      return false;
    }

    if (ContainerLayer* container = aLayer->AsContainerLayer()) {
        if (container->UseIntermediateSurface()) {
            LOGD("Container layer needs intermediate surface");
            return false;
        }
        nsAutoTArray<Layer*, 12> children;
        container->SortChildrenBy3DZOrder(children);

        for (uint32_t i = 0; i < children.Length(); i++) {
            if (!PrepareLayerList(children[i], clip, layerTransform)) {
                return false;
            }
        }
        return true;
    }

    LayerRenderState state = aLayer->GetRenderState();

    if (!state.mSurface.get()) {
      if (aLayer->AsColorLayer() && mColorFill) {
        fillColor = true;
      } else {
          LOGD("%s Layer doesn't have a gralloc buffer", aLayer->Name());
          return false;
      }
    }

    nsIntRect visibleRect = visibleRegion.GetBounds();

    nsIntRect bufferRect;
    if (fillColor) {
        bufferRect = nsIntRect(visibleRect);
    } else {
        nsIntRect layerRect;
        if (state.mHasOwnOffset) {
            bufferRect = nsIntRect(state.mOffset.x, state.mOffset.y,
                                   state.mSize.width, state.mSize.height);
            layerRect = bufferRect;
        } else {
            //Since the buffer doesn't have its own offset, assign the whole
            //surface size as its buffer bounds
            bufferRect = nsIntRect(0, 0, state.mSize.width, state.mSize.height);
            layerRect = bufferRect;
            if (aLayer->GetType() == Layer::TYPE_IMAGE) {
                ImageLayer* imageLayer = static_cast<ImageLayer*>(aLayer);
                if(imageLayer->GetScaleMode() != ScaleMode::SCALE_NONE) {
                  layerRect = nsIntRect(0, 0, imageLayer->GetScaleToSize().width, imageLayer->GetScaleToSize().height);
                }
            }
        }
        // In some cases the visible rect assigned to the layer can be larger
        // than the layer's surface, e.g., an ImageLayer with a small Image
        // in it.
        visibleRect.IntersectRect(visibleRect, layerRect);
    }

    // Buffer rotation is not to be confused with the angled rotation done by a transform matrix
    // It's a fancy PaintedLayer feature used for scrolling
    if (state.BufferRotated()) {
        LOGD("%s Layer has a rotated buffer", aLayer->Name());
        return false;
    }

    const bool needsYFlip = state.OriginBottomLeft() ? true
                                                     : false;

    hwc_rect_t sourceCrop, displayFrame;
    if(!HwcUtils::PrepareLayerRects(visibleRect,
                          layerTransform,
                          layerBufferTransform,
                          clip,
                          bufferRect,
                          needsYFlip,
                          &(sourceCrop),
                          &(displayFrame)))
    {
        return true;
    }

    // OK!  We can compose this layer with hwc.
    int current = mList ? mList->numHwLayers : 0;

    // Do not compose any layer below full-screen Opaque layer
    // Note: It can be generalized to non-fullscreen Opaque layers.
    bool isOpaque = opacity == 0xFF &&
        (state.mFlags & LayerRenderStateFlags::OPAQUE);
    // Currently we perform opacity calculation using the *bounds* of the layer.
    // We can only make this assumption if we're not dealing with a complex visible region.
    bool isSimpleVisibleRegion = visibleRegion.Contains(visibleRect);
    if (current && isOpaque && isSimpleVisibleRegion) {
        nsIntRect displayRect = nsIntRect(displayFrame.left, displayFrame.top,
            displayFrame.right - displayFrame.left, displayFrame.bottom - displayFrame.top);
        if (displayRect.Contains(mScreenRect)) {
            // In z-order, all previous layers are below
            // the current layer. We can ignore them now.
            mList->numHwLayers = current = 0;
            mHwcLayerMap.Clear();
        }
    }

    if (!mList || current >= mMaxLayerCount) {
        if (!ReallocLayerList() || current >= mMaxLayerCount) {
            LOGE("PrepareLayerList failed! Could not increase the maximum layer count");
            return false;
        }
    }

    HwcLayer& hwcLayer = mList->hwLayers[current];
    hwcLayer.displayFrame = displayFrame;
    setCrop(&hwcLayer, sourceCrop);
    buffer_handle_t handle = fillColor ? nullptr : state.mSurface->getNativeBuffer()->handle;
    hwcLayer.handle = handle;

    hwcLayer.flags = 0;
    hwcLayer.hints = 0;
    hwcLayer.blending = isOpaque ? HWC_BLENDING_NONE : HWC_BLENDING_PREMULT;
#if ANDROID_VERSION >= 17
    hwcLayer.compositionType = HWC_FRAMEBUFFER;

    hwcLayer.acquireFenceFd = -1;
    hwcLayer.releaseFenceFd = -1;
#if ANDROID_VERSION >= 18
    hwcLayer.planeAlpha = opacity;
#endif
#else
    hwcLayer.compositionType = HwcUtils::HWC_USE_COPYBIT;
#endif

    if (!fillColor) {
        if (state.FormatRBSwapped()) {
            if (!mRBSwapSupport) {
                LOGD("No R/B swap support in H/W Composer");
                return false;
            }
            hwcLayer.flags |= HwcUtils::HWC_FORMAT_RB_SWAP;
        }

        // Translation and scaling have been addressed in PrepareLayerRects().
        // Given the above and that we checked for PreservesAxisAlignedRectangles()
        // the only possible transformations left to address are
        // square angle rotation and horizontal/vertical reflection.
        //
        // The rotation and reflection permutations total 16 but can be
        // reduced to 8 transformations after eliminating redundancies.
        //
        // All matrices represented here are in the form
        //
        // | xx  xy |
        // | yx  yy |
        //
        // And ignore scaling.
        //
        // Reflection is applied before rotation
        gfx::Matrix rotation = layerTransform;
        // Compute fuzzy zero like PreservesAxisAlignedRectangles()
        if (fabs(rotation._11) < 1e-6) {
            if (rotation._21 < 0) {
                if (rotation._12 > 0) {
                    // 90 degree rotation
                    //
                    // |  0  -1  |
                    // |  1   0  |
                    //
                    hwcLayer.transform = HWC_TRANSFORM_ROT_90;
                    LOGD("Layer rotated 90 degrees");
                }
                else {
                    // Horizontal reflection then 90 degree rotation
                    //
                    // |  0  -1  | | -1   0  | = |  0  -1  |
                    // |  1   0  | |  0   1  |   | -1   0  |
                    //
                    // same as vertical reflection then 270 degree rotation
                    //
                    // |  0   1  | |  1   0  | = |  0  -1  |
                    // | -1   0  | |  0  -1  |   | -1   0  |
                    //
                    hwcLayer.transform = HWC_TRANSFORM_ROT_90 | HWC_TRANSFORM_FLIP_H;
                    LOGD("Layer vertically reflected then rotated 270 degrees");
                }
            } else {
                if (rotation._12 < 0) {
                    // 270 degree rotation
                    //
                    // |  0   1  |
                    // | -1   0  |
                    //
                    hwcLayer.transform = HWC_TRANSFORM_ROT_270;
                    LOGD("Layer rotated 270 degrees");
                }
                else {
                    // Vertical reflection then 90 degree rotation
                    //
                    // |  0   1  | | -1   0  | = |  0   1  |
                    // | -1   0  | |  0   1  |   |  1   0  |
                    //
                    // Same as horizontal reflection then 270 degree rotation
                    //
                    // |  0  -1  | |  1   0  | = |  0   1  |
                    // |  1   0  | |  0  -1  |   |  1   0  |
                    //
                    hwcLayer.transform = HWC_TRANSFORM_ROT_90 | HWC_TRANSFORM_FLIP_V;
                    LOGD("Layer horizontally reflected then rotated 270 degrees");
                }
            }
        } else if (rotation._11 < 0) {
            if (rotation._22 > 0) {
                // Horizontal reflection
                //
                // | -1   0  |
                // |  0   1  |
                //
                hwcLayer.transform = HWC_TRANSFORM_FLIP_H;
                LOGD("Layer rotated 180 degrees");
            }
            else {
                // 180 degree rotation
                //
                // | -1   0  |
                // |  0  -1  |
                //
                // Same as horizontal and vertical reflection
                //
                // | -1   0  | |  1   0  | = | -1   0  |
                // |  0   1  | |  0  -1  |   |  0  -1  |
                //
                hwcLayer.transform = HWC_TRANSFORM_ROT_180;
                LOGD("Layer rotated 180 degrees");
            }
        } else {
            if (rotation._22 < 0) {
                // Vertical reflection
                //
                // |  1   0  |
                // |  0  -1  |
                //
                hwcLayer.transform = HWC_TRANSFORM_FLIP_V;
                LOGD("Layer rotated 180 degrees");
            }
            else {
                // No rotation or reflection
                //
                // |  1   0  |
                // |  0   1  |
                //
                hwcLayer.transform = 0;
            }
        }

        const bool needsYFlip = state.OriginBottomLeft() ? true
                                                         : false;

        if (needsYFlip) {
           // Invert vertical reflection flag if it was already set
           hwcLayer.transform ^= HWC_TRANSFORM_FLIP_V;
        }
        hwc_region_t region;
        if (visibleRegion.GetNumRects() > 1) {
            mVisibleRegions.push_back(HwcUtils::RectVector());
            HwcUtils::RectVector* visibleRects = &(mVisibleRegions.back());
            if(!HwcUtils::PrepareVisibleRegion(visibleRegion,
                                     layerTransform,
                                     layerBufferTransform,
                                     clip,
                                     bufferRect,
                                     visibleRects)) {
                return true;
            }
            region.numRects = visibleRects->size();
            region.rects = &((*visibleRects)[0]);
        } else {
            region.numRects = 1;
            region.rects = &(hwcLayer.displayFrame);
        }
        hwcLayer.visibleRegionScreen = region;
    } else {
        hwcLayer.flags |= HwcUtils::HWC_COLOR_FILL;
        ColorLayer* colorLayer = aLayer->AsColorLayer();
        if (colorLayer->GetColor().a < 1.0) {
            LOGD("Color layer has semitransparency which is unsupported");
            return false;
        }
        hwcLayer.transform = colorLayer->GetColor().Packed();
    }

    mHwcLayerMap.AppendElement(static_cast<LayerComposite*>(aLayer->ImplData()));
    mList->numHwLayers++;
    return true;
}
Пример #22
0
JNIEXPORT void JNICALL Java_com_example_hellohalide_CameraPreview_processFrame(JNIEnv * env, jobject obj, jbyteArray jSrc, jobject surf) {

    halide_set_error_handler(handler);

    unsigned char *src = (unsigned char *)env->GetByteArrayElements(jSrc, NULL);

    ANativeWindow *win = ANativeWindow_fromSurface(env, surf);
    ANativeWindow_acquire(win);

    static bool first_call = true;
    static unsigned counter = 0;
    static unsigned times[16];
    if (first_call) {
      LOGD("Resetting buffer format");
      ANativeWindow_setBuffersGeometry(win, 640, 360, 0);
      first_call = false;
      for (int t = 0; t < 16; t++) times[t] = 0;
    }

    ANativeWindow_Buffer buf;
    ARect rect = {0, 0, 640, 360};
    ANativeWindow_lock(win, &buf, &rect);

    uint8_t *dst = (uint8_t *)buf.bits;
    buffer_t srcBuf = {0}, dstBuf = {0};
    srcBuf.host = (uint8_t *)src;
    srcBuf.extent[0] = 642;
    srcBuf.extent[1] = 362;
    srcBuf.extent[2] = 1;
    srcBuf.extent[3] = 1;
    srcBuf.stride[0] = 1;
    srcBuf.stride[1] = 640;
    srcBuf.min[0] = -1;
    srcBuf.min[1] = -1;
    srcBuf.elem_size = 1;

    dstBuf.host = dst;
    dstBuf.extent[0] = 640;
    dstBuf.extent[1] = 360;
    dstBuf.extent[2] = 1;
    dstBuf.extent[3] = 1;
    dstBuf.stride[0] = 1;
    dstBuf.stride[1] = 640;
    dstBuf.min[0] = 0;
    dstBuf.min[1] = 0;
    dstBuf.elem_size = 1;

    timeval t1, t2;
    gettimeofday(&t1, NULL);
    halide(&srcBuf, &dstBuf);
    gettimeofday(&t2, NULL);
    unsigned elapsed = (t2.tv_sec - t1.tv_sec)*1000000 + (t2.tv_usec - t1.tv_usec);

    times[counter & 15] = elapsed;
    counter++;
    unsigned min = times[0];
    for (int i = 1; i < 16; i++) {
        if (times[i] < min) min = times[i];
    }
    LOGD("Time taken: %d (%d)", elapsed, min);

    // Just copy over chrominance untouched
    memcpy(dst + 640*360, src + 640*480, 320*180);
    memcpy(dst + 640*360 + 320*180, src + 640*480 + 320*240, 320*180);

    ANativeWindow_unlockAndPost(win);
    ANativeWindow_release(win);

    env->ReleaseByteArrayElements(jSrc, (jbyte *)src, 0);
}
Пример #23
0
static bool run_daemon(void)
{
    int fd;
    struct sockaddr_un addr;

    fd = socket(AF_LOCAL, SOCK_STREAM, 0);
    if (fd < 0) {
        LOGE("Failed to create socket: %s", strerror(errno));
        return false;
    }

    auto close_fd = util::finally([&] {
        close(fd);
    });

    char abs_name[] = "\0mbtool.daemon";
    size_t abs_name_len = sizeof(abs_name) - 1;

    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_LOCAL;
    memcpy(addr.sun_path, abs_name, abs_name_len);

    // Calculate correct length so the trailing junk is not included in the
    // abstract socket name
    socklen_t addr_len = offsetof(struct sockaddr_un, sun_path) + abs_name_len;

    if (bind(fd, (struct sockaddr *) &addr, addr_len) < 0) {
        LOGE("Failed to bind socket: %s", strerror(errno));
        LOGE("Is another instance running?");
        return false;
    }

    if (listen(fd, 3) < 0) {
        LOGE("Failed to listen on socket: %s", strerror(errno));
        return false;
    }

    // Eat zombies!
    // SIG_IGN reaps zombie processes (it's not just a dummy function)
    struct sigaction sa;
    sa.sa_handler = SIG_IGN;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGCHLD, &sa, 0) < 0) {
        LOGE("Failed to set SIGCHLD handler: %s", strerror(errno));
        return false;
    }

    LOGD("Socket ready, waiting for connections");

    int client_fd;
    while ((client_fd = accept(fd, nullptr, nullptr)) >= 0) {
        pid_t child_pid = fork();
        if (child_pid < 0) {
            LOGE("Failed to fork: %s", strerror(errno));
        } else if (child_pid == 0) {
            bool ret = client_connection(client_fd);
            close(client_fd);
            _exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
        }
        close(client_fd);
    }

    if (client_fd < 0) {
        LOGE("Failed to accept connection on socket: %s", strerror(errno));
        return false;
    }

    return true;
}
Пример #24
0
/* convert register to temperature  */
int BattThermistorConverTemp(int Res)
{
	int i=0;
	int RES1=0,RES2=0;
	int TBatt_Value=-200,TMP1=0,TMP2=0;

	#ifdef BATTERY_TYPE_Z3
	BATT_TEMPERATURE Batt_Temperature_Table[] = {
		{-20,483954},
		{-15,360850},
		{-10,271697},
		{ -5,206463},
		{  0,158214},
		{  5,122259},
		{ 10,95227},
		{ 15,74730},
		{ 20,59065},
		{ 25,47000},
		{ 30,37643},
		{ 35,30334},
		{ 40,24591},
		{ 45,20048},
		{ 50,16433},
		{ 55,13539},
		{ 60,11210}		
	};
	#else
	BATT_TEMPERATURE Batt_Temperature_Table[] = {
		{-20,68237},
		{-15,53650},
		{-10,42506},
		{ -5,33892},
		{  0,27219},
		{  5,22021},
		{ 10,17926},
		{ 15,14674},
		{ 20,12081},
		{ 25,10000},
		{ 30,8315},
		{ 35,6948},
		{ 40,5834},
		{ 45,4917},
		{ 50,4161},
		{ 55,3535},
		{ 60,3014}
	};
	#endif

	LOGD(TAG "###### %d <-> %d ######\r\n", Batt_Temperature_Table[9].BatteryTemp, Batt_Temperature_Table[9].TemperatureR);
	
	if(Res>=Batt_Temperature_Table[0].TemperatureR)
	{
		#ifdef CONFIG_DEBUG_MSG_NO_BQ27500
		printk("Res>=%d\n", Batt_Temperature_Table[0].TemperatureR);
		#endif
		TBatt_Value = -20;
	}
	else if(Res<=Batt_Temperature_Table[16].TemperatureR)
	{
		#ifdef CONFIG_DEBUG_MSG_NO_BQ27500
		printk("Res<=%d\n", Batt_Temperature_Table[16].TemperatureR);
		#endif
		TBatt_Value = 60;
	}
	else
	{
		RES1=Batt_Temperature_Table[0].TemperatureR;
		TMP1=Batt_Temperature_Table[0].BatteryTemp;

		for(i=0;i<=16;i++)
		{
			if(Res>=Batt_Temperature_Table[i].TemperatureR)
			{
				RES2=Batt_Temperature_Table[i].TemperatureR;
				TMP2=Batt_Temperature_Table[i].BatteryTemp;
				break;
			}
			else
			{
				RES1=Batt_Temperature_Table[i].TemperatureR;
				TMP1=Batt_Temperature_Table[i].BatteryTemp;
			}
		}
		
		TBatt_Value = (((Res-RES2)*TMP1)+((RES1-Res)*TMP2))/(RES1-RES2);
	}

	#ifdef CONFIG_DEBUG_MSG_NO_BQ27500
	printk("BattThermistorConverTemp() : TBatt_Value = %d\n",TBatt_Value);
	#endif

	return TBatt_Value;	
}
Пример #25
0
int hdmi_entry(struct ftm_param *param, void *priv)
{
    bool exit = false;
    hdmi_module *hdmi = (hdmi_module *)priv;
    struct itemview *iv;

    LOGD(TAG "hdmi_entry\n");

     /* show text view */
    if (!hdmi->itm_view) {
        iv = ui_new_itemview();
        if (!iv) {
            LOGD(TAG "No memory for item view");
            return -1;
        }
        hdmi->itm_view = iv;
    }

    iv = hdmi->itm_view;

    //init item view
    memset(&hdmi->info[0], 0, sizeof(hdmi->info));
    memset(&hdmi->info[0], '\n', 10);
    init_text(&hdmi->title, param->name, COLOR_YELLOW);
    init_text(&hdmi->text, &hdmi->info[0], COLOR_YELLOW);

    iv->set_title(iv, &hdmi->title);
    iv->set_items(iv, hdmi_item, 0);
    iv->set_text(iv, &hdmi->text);

    //iv->redraw(iv);

    if(hdmi_enable())
    {
        LOGD(TAG "hdmi test fail\n");
        //hdmi->text.color = COLOR_RED;
        sprintf(hdmi->info, "HDMI "uistr_fail"\n");
    }
    else
    {
        LOGD(TAG "hdmi test pass\n");
        //hdmi->text.color = COLOR_GREEN;
        sprintf(hdmi->info, "HDMI "uistr_pass"\n");
    }

    while(!exit)
    {
        switch(iv->run(iv, NULL))
        {
        case ITEM_PASS:
            hdmi->module->test_result = FTM_TEST_PASS;
            exit = true;
            break;
        case ITEM_FAIL:
            hdmi->module->test_result = FTM_TEST_FAIL;
            exit = true;
            break;
        case -1:
            exit = true;
            break;
        default:
            break;
        }
    }

    //hdmi_disable();

    return 0;
}
Пример #26
0
int battery_entry(struct ftm_param *param, void *priv)
{
    char *ptr;
    int chosen;
    bool exit = false;
    struct batteryFTM *batt = (struct batteryFTM *)priv;
    struct textview *tv;    
	struct itemview *iv;
	//auto test
	int temp=0;
	int temp_v_bat=0;
	int temp_chr_cuttent=0;
	int temp_v_chr=0;
	int temp_v_bat_temp=0;
	unsigned long i=0;
	unsigned long i_loop_time=100;

    LOGD(TAG "%s\n", __FUNCTION__);

    init_text(&batt->title, param->name, COLOR_YELLOW);
    init_text(&batt->text, &batt->info[0], COLOR_YELLOW);
    init_text(&batt->left_btn, "Fail", COLOR_YELLOW);
    init_text(&batt->center_btn, "Pass", COLOR_YELLOW);
    init_text(&batt->right_btn, "Back", COLOR_YELLOW);

    battery_update_info(batt, batt->info);

    /* show text view */
    batt->exit_thd = false;     

#if 0
    pthread_create(&batt->batt_update_thd, NULL, battery_update_thread, priv);

    tv = &batt->tv;
    ui_init_textview(tv, battery_key_handler, (void*)batt);
    tv->set_title(tv, &batt->title);
    tv->set_text(tv, &batt->text);
    tv->set_btn(tv, &batt->left_btn, &batt->center_btn, &batt->right_btn);
    tv->run(tv);

    pthread_join(batt->batt_update_thd, NULL);
#else
	if (!batt->iv) {
        iv = ui_new_itemview();
        if (!iv) {
            LOGD(TAG "No memory");
            return -1;
        }
        batt->iv = iv;
    }
    
    iv = batt->iv;
    iv->set_title(iv, &batt->title);
    iv->set_items(iv, battery_items, 0);
    iv->set_text(iv, &batt->text);
	iv->start_menu(iv,0);

    #if 1
	iv->redraw(iv);


	return_data.battery.current = 0;
	return_data.battery.voltage = 0;

  //auto test - if no charger, return fail

   #ifdef FEATURE_FTM_VBAT_TEMP_CHECK
   //auto test - V bat temp	
   temp_v_bat_temp = get_v_bat_temp();
   if(temp_v_bat_temp < AUTO_TEST_VBAT_TEMP_MIN || temp_v_bat_temp > AUTO_TEST_VBAT_TEMP_MAX)
   {
     LOGD(TAG "[FTM_BAT 5] VBatTemp = %d , return fail\n", temp_v_chr);		
     batt->mod->test_result = FTM_TEST_FAIL;
     return 0;
   }
   #endif
  
  temp_v_chr = get_v_charger();  
  if(temp_v_chr < AUTO_TEST_VCHR_VALUE)
  {
    LOGD(TAG "[FTM_BAT 0] %d < %d => no charger, return fail\n", temp_v_chr, AUTO_TEST_VCHR_VALUE);		
    batt->mod->test_result = FTM_TEST_FAIL;
    return 0;
  }

	//auto test - V_bat
	temp_v_bat = get_v_bat_sen();
	return_data.battery.voltage = temp_v_bat;
	if(temp_v_bat < AUTO_TEST_VBAT_VALUE)
	{
		LOGD(TAG "[FTM_BAT 1] %d,%d,%d,%d,%d,%d,%d\n", 
			temp_v_bat, temp_chr_cuttent, i, i_loop_time, 
			AUTO_TEST_VBAT_VALUE, AUTO_TEST_THD_VALUE, AUTO_TEST_CHR_CURRENT_VALUE);
		
	    batt->mod->test_result = FTM_TEST_FAIL;
		return 0;
	}
	if(temp_v_bat > AUTO_TEST_THD_VALUE)
	{
		LOGD(TAG "[FTM_BAT 2] %d,%d,%d,%d,%d,%d,%d\n", 
			temp_v_bat, temp_chr_cuttent, i, i_loop_time, 
			AUTO_TEST_VBAT_VALUE, AUTO_TEST_THD_VALUE, AUTO_TEST_CHR_CURRENT_VALUE);
    
		//ignore I_charging test because the battery is full, no charging current
	    batt->mod->test_result = FTM_TEST_PASS;		
		return 0;
	}

	//auto test - I_charging
	for(i=0 ; i<i_loop_time ; i++)
	{
		temp_chr_cuttent = get_charging_current();
		return_data.battery.current = temp_chr_cuttent;
		
		if(temp_chr_cuttent > AUTO_TEST_CHR_CURRENT_VALUE)
			break;
	}	
	
	
	if(i >= i_loop_time)
	{
		LOGD(TAG "[FTM_BAT 3] %d,%d,%d,%d,%d,%d,%d\n", 
			temp_v_bat, temp_chr_cuttent, i, i_loop_time, 
			AUTO_TEST_VBAT_VALUE, AUTO_TEST_THD_VALUE, AUTO_TEST_CHR_CURRENT_VALUE);
		
	    batt->mod->test_result = FTM_TEST_FAIL;
		return 0;
	}
	else
	{
		LOGD(TAG "[FTM_BAT 4] %d,%d,%d,%d,%d,%d,%d\n", 
			temp_v_bat, temp_chr_cuttent, i, i_loop_time, 
			AUTO_TEST_VBAT_VALUE, AUTO_TEST_THD_VALUE, AUTO_TEST_CHR_CURRENT_VALUE);
		
		batt->mod->test_result = FTM_TEST_PASS;
		return 0;
	}	


	#else
    pthread_create(&batt->batt_update_thd, NULL, battery_update_iv_thread, priv);
    do {
        chosen = iv->run(iv, &exit);
        switch (chosen) {
		case ITEM_AC_CHARGER:
			set_Charger_Current(AC_CHARGER_CURRENT);
			break;
		case ITEM_USB_CHARGER:	
			set_Charger_Current(USB_CHARGER_CURRENT);
			break;
			
        case ITEM_PASS:
        case ITEM_FAIL:
            if (chosen == ITEM_PASS) {
                batt->mod->test_result = FTM_TEST_PASS;
            } else if (chosen == ITEM_FAIL) {
                batt->mod->test_result = FTM_TEST_FAIL;
            }           
            exit = true;
            break;
        }
        
        if (exit) {
            batt->exit_thd = true;
            break;
        }        
    } while (1);
    pthread_join(batt->batt_update_thd, NULL);
#endif	
	//do nothing
#endif	

    return 0;
}
Пример #27
0
void writeIfd0(FILE *fptr, DngWriter *writer)
{
    /* Write the header */
    WriteHexString(fptr,"4d4d002a");    /* Big endian & TIFF identifier */
    offset = writer->rawwidht * writer->rawheight * 3 + 8;
    putc((offset & 0xff000000) / 16777216,fptr);
    putc((offset & 0x00ff0000) / 65536,fptr);
    putc((offset & 0x0000ff00) / 256,fptr);
    putc((offset & 0x000000ff),fptr);

    //raw file ?
    /* Write the binary data */
    for (j=0;j<ny;j++) {
        for (i=0;i<nx;i++) {
            //... calculate the RGB value between 0 and 255 ...
            fputc(red,fptr);
            fputc(green,fptr);
            fputc(blue,fptr);
        }
    }

    /* Write the footer */
    WriteHexString(fptr,"000e");  /* The number of directory entries (14) */

    //Use Tiff Tags for ints added To DngWriter Header file

    WriteHexString(fptr,TagGen(TIFFTAG_SUBFILETYPE,Sshort));  /* The number of directory entries (14) */

    //TIFFSetField (tif, TIFFTAG_SUBFILETYPE, 0);

    /* Width tag, short int */
    WriteHexString(fptr,"0100000300000001");
    fputc((writer->rawwidht & 0xff00) / 256,fptr);    /* Image width */
    fputc((writer->rawwidht & 0x00ff),fptr);
    WriteHexString(fptr,"0000");

    /* Height tag, short int */
    WriteHexString(fptr,"0101000300000001");
    fputc((writer->rawheight & 0xff00) / 256,fptr);    /* Image height */
    fputc((writer->rawheight & 0x00ff),fptr);
    WriteHexString(fptr,"0000");

    LOGD("subfiletype");

    assert(TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, writer->rawwidht) != 0);
    LOGD("width");


    assert(TIFFSetField(tif, TIFFTAG_IMAGELENGTH, writer->rawheight) != 0);
    LOGD("height");


    if(writer->rawType > 0)
        assert(TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16) != 0);
    else
        assert(TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 10) != 0);
    LOGD("bitspersample");
    assert(TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_CFA) != 0);
    LOGD("PhotometricCFA");
    //assert(TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 480/2) != 0);
    assert(TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE) != 0);
    LOGD("Compression");
    TIFFSetField (tif, TIFFTAG_SAMPLESPERPIXEL, 1);
    LOGD("sampelsperpixel");
    TIFFSetField(tif, TIFFTAG_MAKE, writer->_make);
    LOGD("make");
    TIFFSetField(tif, TIFFTAG_MODEL, writer->_model);
    LOGD("model");
    try
    {
        if(0 == strcmp(writer->_orientation,"0") )
            TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
        if(0 == strcmp(writer->_orientation,"90") )
            TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_RIGHTTOP);
        if(0 == strcmp(writer->_orientation,"180") )
            TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_BOTRIGHT);
        if(0 == strcmp(writer->_orientation,"270") )
            TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_LEFTBOT);
        LOGD("orientation");
    }
    catch(...)
    {
        LOGD("Caught NULL NOT SET Orientation");
    }
    assert(TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG) != 0);
    LOGD("planarconfig");
    //assert(TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3) != 0);
    TIFFSetField(tif, TIFFTAG_SOFTWARE, "FreedCam by Troop");
    LOGD("software");
    TIFFSetField(tif, TIFFTAG_DNGVERSION, "\001\003\0\0");
    TIFFSetField(tif, TIFFTAG_DNGBACKWARDVERSION, "\001\001\0\0");
    LOGD("dngversion");
    TIFFSetField(tif, TIFFTAG_UNIQUECAMERAMODEL, "SonyIMX");
    LOGD("CameraModel");
    TIFFSetField(tif, TIFFTAG_IMAGEDESCRIPTION, writer->_imagedescription);
    LOGD("imagedescription");
    TIFFSetField(tif, TIFFTAG_COLORMATRIX1, 9, writer->colorMatrix2);
    LOGD("colormatrix1");
    TIFFSetField(tif, TIFFTAG_ASSHOTNEUTRAL, 3, writer->neutralColorMatrix);
    LOGD("neutralMatrix");
    TIFFSetField(tif, TIFFTAG_CALIBRATIONILLUMINANT1, 21);

    TIFFSetField(tif, TIFFTAG_CALIBRATIONILLUMINANT2, 17);

    TIFFSetField(tif, TIFFTAG_COLORMATRIX2, 9, writer->colorMatrix1);

    static const float cam_foward1[] = {
            // R 	G     	B
            0.6648, 0.2566, 0.0429, 0.197, 0.9994, -0.1964, -0.0894, -0.2304, 1.145
    };

    static const float cam_foward2[] = {
            0.6617, 0.3849, -0.0823, 0.24, 1.1138, -0.3538, -0.0062, -0.1147, 0.946
    };

    static const float cam_nex_foward1[] = {
            // R 	G     	B
            0.6328, 0.0469, 0.2813, 0.1641, 0.7578, 0.0781, -0.0469, -0.6406, 1.5078
    };

    static const float cam_nex_foward2[] = {
            0.7578, 0.0859, 0.1172, 0.2734, 0.8281, -0.1016, 0.0156, -0.2813, 1.0859
    };
    TIFFSetField(tif, TIFFTAG_FOWARDMATRIX1, 9,  writer->fowardMatrix2);
    TIFFSetField(tif, TIFFTAG_FOWARDMATRIX2, 9,  writer->fowardMatrix1);
    static const float testNR[] = {
            0.00051471, 0, 0.00051471,0, 0.00051471, 0};
    TIFFSetField(tif, TIFFTAG_NOISEPROFILE, 6,  writer->noiseMatrix);



    LOGD("colormatrix2");
    //////////////////////////////IFD POINTERS///////////////////////////////////////
    ///GPS//////////
    // TIFFSetField (tif, TIFFTAG_GPSIFD, gpsIFD_offset);
    ///EXIF////////

}
Пример #28
0
// If the RAS autodial service is running, use it. Otherwise, dial
// the default RAS connection. There are two possible RAS dialogs:
// one that dials a single entry, and one that lets the user choose which
// to dial. If there is only one connection entry in the phone book, or
// there are multiple entries but one is defined as the default, we'll use
// the single entry dial dialog. If there are multiple connection entries,
// and none is specified as default, we'll bring up the diallog which lets
// the user select the connection entry to use.
//
// Return values:
//  NS_OK: dialing was successful and caller should retry
//  all other values indicate that the caller should not retry
nsresult nsAutodial::DialDefault(const PRUnichar* hostName)
{
    mDontRetryUntil = 0;

    if (mAutodialBehavior == AUTODIAL_NEVER)
    {
        return NS_ERROR_FAILURE;    // don't retry the network error
    }

    // If already a RAS connection, bail.
    if (IsRASConnected())
    {
        LOGD(("Autodial: Not dialing: active connection."));
        return NS_ERROR_FAILURE;    // don't retry
    }

    // If no dialup connections configured, bail.
    if (mNumRASConnectionEntries <= 0)
    {
        LOGD(("Autodial: Not dialing: no entries."));
        return NS_ERROR_FAILURE;    // don't retry
    }


    // If autodial service is running, let it dial. In order for it to dial more
    // reliably, we have to add the target address to the autodial database.
    // This is the only way the autodial service dial if there is a network
    // adapter installed. But even then it might not dial. We have to assume that
    // it will though, or we could end up with two attempts to dial on the same
    // network error if the user cancels the first one: one from the service and
    // one from us.
    // See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/rras/ras4over_3dwl.asp
    if (mAutodialBehavior == AUTODIAL_USE_SERVICE)
    {
        AddAddressToAutodialDirectory(hostName);
        return NS_ERROR_FAILURE;    // don't retry
    }

    // Do the dialing ourselves.
    else
    {
        // If a default dial entry is configured, use it.
        if (mDefaultEntryName[0] != '\0') 
        {
            LOGD(("Autodial: Dialing default: %s.",mDefaultEntryName));

            RASDIALDLG rasDialDlg;
            memset(&rasDialDlg, 0, sizeof(rasDialDlg));
            rasDialDlg.dwSize = sizeof(rasDialDlg);

            BOOL dialed = 
             RasDialDlgW(nsnull, mDefaultEntryName, nsnull, &rasDialDlg);

            if (!dialed)
            {
                if (rasDialDlg.dwError != 0)
                {
                    LOGE(("Autodial ::RasDialDlg failed: Error: %d.", 
                     rasDialDlg.dwError));
                }
                else
                {
                    mDontRetryUntil = PR_IntervalNow() + PR_SecondsToInterval(NO_RETRY_PERIOD_SEC);
                    LOGD(("Autodial: User cancelled dial."));
                }
                return NS_ERROR_FAILURE;    // don't retry
            }

            LOGD(("Autodial: RAS dialup connection successful."));
        }

        // If no default connection specified, open the dialup dialog that lets
        // the user specifiy which connection to dial.
        else
        {
            LOGD(("Autodial: Prompting for phonebook entry."));

            RASPBDLG rasPBDlg;
            memset(&rasPBDlg, 0, sizeof(rasPBDlg));
            rasPBDlg.dwSize = sizeof(rasPBDlg);
 
            BOOL dialed = RasPhonebookDlgW(nsnull, nsnull, &rasPBDlg);

            if (!dialed)
            {
                if (rasPBDlg.dwError != 0)
                {
                    LOGE(("Autodial: ::RasPhonebookDlg failed: Error = %d.", 
                     rasPBDlg.dwError));
                }
                else
                {
                    mDontRetryUntil = PR_IntervalNow() + PR_SecondsToInterval(NO_RETRY_PERIOD_SEC);
                    LOGD(("Autodial: User cancelled dial."));
                }

                return NS_ERROR_FAILURE;    // don't retry
            }

            LOGD(("Autodial: RAS dialup connection successful."));
        }
    }

    // Retry because we just established a dialup connection.
    return NS_OK;
}
int dexopt(const char *apk_path, uid_t uid, int is_public)
{
    struct utimbuf ut;
    struct stat apk_stat, dex_stat;
    char dex_path[PKG_PATH_MAX];
    char dexopt_flags[PROPERTY_VALUE_MAX];
    char *end;
    int res, zip_fd=-1, odex_fd=-1;

        /* Before anything else: is there a .odex file?  If so, we have
         * pre-optimized the apk and there is nothing to do here.
         */
    if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
        return -1;
    }

    if (strncmp(apk_path, "/system", 7) != 0) {
        zipalign(apk_path, uid, is_public);
    }

    /* platform-specific flags affecting optimization and verification */
    property_get("dalvik.vm.dexopt-flags", dexopt_flags, "");

    strcpy(dex_path, apk_path);
    end = strrchr(dex_path, '.');
    if (end != NULL) {
        strcpy(end, ".odex");
        if (stat(dex_path, &dex_stat) == 0) {
            return 0;
        }
    }

    if (create_cache_path(dex_path, apk_path)) {
        return -1;
    }

    memset(&apk_stat, 0, sizeof(apk_stat));
    stat(apk_path, &apk_stat);

    zip_fd = open(apk_path, O_RDONLY, 0);
    if (zip_fd < 0) {
        LOGE("dexopt cannot open '%s' for input\n", apk_path);
        return -1;
    }

    unlink(dex_path);
    odex_fd = open(dex_path, O_RDWR | O_CREAT | O_EXCL, 0644);
    if (odex_fd < 0) {
        LOGE("dexopt cannot open '%s' for output\n", dex_path);
        goto fail;
    }
    if (fchown(odex_fd, AID_SYSTEM, uid) < 0) {
        LOGE("dexopt cannot chown '%s'\n", dex_path);
        goto fail;
    }
    if (fchmod(odex_fd,
               S_IRUSR|S_IWUSR|S_IRGRP |
               (is_public ? S_IROTH : 0)) < 0) {
        LOGE("dexopt cannot chmod '%s'\n", dex_path);
        goto fail;
    }

    LOGD("DexInv: --- BEGIN '%s' ---\n", apk_path);

    pid_t pid;
    pid = fork();
    if (pid == 0) {
        /* child -- drop privileges before continuing */
        if (setgid(uid) != 0) {
            LOGE("setgid(%d) failed during dexopt\n", uid);
            exit(64);
        }
        if (setuid(uid) != 0) {
            LOGE("setuid(%d) during dexopt\n", uid);
            exit(65);
        }
        if (flock(odex_fd, LOCK_EX | LOCK_NB) != 0) {
            LOGE("flock(%s) failed: %s\n", dex_path, strerror(errno));
            exit(66);
        }

        run_dexopt(zip_fd, odex_fd, apk_path, dexopt_flags);
        exit(67);   /* only get here on exec failure */
    } else {
        res = wait_dexopt(pid, apk_path);
        if (res != 0) {
            LOGE("dexopt failed on '%s' res = %d\n", dex_path, res);
            goto fail;
        }
    }

    ut.actime = apk_stat.st_atime;
    ut.modtime = apk_stat.st_mtime;
    utime(dex_path, &ut);
    
    close(odex_fd);
    close(zip_fd);
    return 0;

fail:
    if (odex_fd >= 0) {
        close(odex_fd);
        unlink(dex_path);
    }
    if (zip_fd >= 0) {
        close(zip_fd);
    }
    return -1;
}
Пример #30
0
int CameraHardware::beginAutoFocusThread(void *cookie)
{
    CameraHardware *c = (CameraHardware *)cookie;
    LOGD("beginAutoFocusThread");
    return c->autoFocusThread();
}