Thursday, July 14, 2016

C언어 Quick Soft 예제

int data[7] = { 3,5,1,2,6,9,7 };

void swapInt(int &a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}

void printArr(int arr[]) {
printf("arr=");
for (int i = 0; i < 7; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

void quickSort(int arr[], int left, int right)
{
printf("left=%d right=%d\n", left, right);

int i = left;
int j = right;
printArr(arr);

int pivotIndex = (left + right) / 2;
int pivot = arr[pivotIndex];
printf("pivotIndex=%d pivot=%d\n", pivotIndex, pivot);

while (i <= j) {
// 피봇을 기준으로 left의 값이 pivot의 값보다 큰 것을 찾는다.(잘못 놓여진 것을 찾음)
while (arr[i] < pivot) {
printf("arr[%d]=%d i++\n", i, arr[i]);
i++;
}
// 피봇을 기준으로 right의 값이 pivot의 값보다 작은 것을 찾는다.(잘못 놓여진 것을 찾음)
while (arr[j] > pivot) {
printf("arr[%d]=%d j--\n", j, arr[j]);
j--;
}

// 인덱스가 정상적인 상황일때 스왑한다.
if (i <= j) {
printf("swap begin %d %d\n", i, j);
swapInt(arr[i], arr[j]);
printArr(arr);
i++;
j--;
printf("swap end %d %d\n", i, j);
}
}

// 나머지 좌우에 대해서 다시 퀵소트 한다.
if (left < j) {
quickSort(arr, left, j);
}

if (i < right) {
quickSort(arr, i, right);
}
}


int main()
{
quickSort(data, 0, 6);
printf("data=");
for (int i = 0; i < 7; i++) {
printf("%d ", data[i]);
}
printf("\n");
return 0;
}

Android Camera2 API 기능

간단히 Camera2 API가 할 수 있는 기능은

- Burst capture at full resolution at up to 30fps.
센서 풀 해상도로 초당 30프레임의 사진을 찍을 수 있습니다.

- RAW (dng) image capture (more on this later).
DNG 파일로 캡처할 수 있습니다.

- Full manual focus.
흉내만 낸 수동초점이 아닌 진짜 리얼 풀 매뉴얼 포커스가 가능합니다.

- Faster autofocus
좀더 빠른 자동초점을 잡습니다.

- A smoother viewfinder.
부드러운 미리보기를 볼 수 있습니다.

- Full resolution video.
센서 풀 해상도의 영상을 저장할 수 있습니다.

- No viewfinder swapping when switching between modes.
모드변경을 위해 미리보는 화면 변경되는 과정이 없습니다.

- Implement granular settings before capture.
세부적인 설정이 가능합니다.

- Request target frame rates.
프레임레이트를 정할 수 있습니다.

- Access to raw sensor data.
RAW 데이타에 접근할 수 있습니다. 이전에는 포스트프로세스 애프터프로세스를 통해 JPG로 저장되었죠

- Flash firing support
플래쉬 터뜨리는 방법을 조절할 수 있습니다. 상상이지만 모델링 플래쉬도 구현되겠죠?

- Video HDR
HDR 영상을 지원합니다.

- Focus stacking.
Burst로 한 사진에 여러 초점 사진을 찍을 수 있습니다.

- Exposure bracketing
Burst로 노출 브라켓팅 (여러 노출로 찍는 기법입니다)을 찍을 수 있습니다.

Wednesday, July 13, 2016

Android ANR 디버깅 방법

안드로이드에서 ANR 디버깅 방법
-Method profiling
-Thread monitor
-StrictMode 정의
Main Thread에서는 시간이 많이 소모될 수 있는, 동작을 규정하고 막을 수 있다.
그 규정은 안드로이드에서 제공하는 범위에서 개발자가 정한다.
그 규정 위반시 안드로이드에서 제공하는 범위에서 처리를 할 수 있다.
-Dropbox 사용(제조사, 에뮬레이터)

http://cluster1.cafe.daum.net/_c21_/bbs_search_read?grpid=1MWA2&fldid=aAfL&datanum=99&openArticle=true&docid=1MWA2%7CaAfL%7C99%7C20110712112022

동영상 프레임의 종류 I/P/B 프레임(i-frame, p-frame, b-frame)

I 프레임 - Infra Frame 의 약자로, 쉽게 말해 키 프레임 입니다. 이것은 JPEG 같은 방식으로 소스로부터 직접 압축되어 온 전체 그림이죠. 가장 화질도 좋지만 가장 용량도 큽니다.
P 프레임 - Previous 또는 Predicted Frame 이라 불리며, 이전에 나온 키 프레임의 정보를 바탕으로 구성된 프레임 입니다. 화질/용량 둘 다 중간급입니다.
B 프레임 - Bidirectional Frame 의 약자로, 전후의 I/P 프레임의 정보를 바탕으로 구성된 프레임 입니다. 화질/용량이 다 최하급입니다.

Java GC root

GC의 reachability를 판단할때는 다음과 같은 GC root 노드를 기준으로 판단한다. 그 GC root에 해당하는 것들은 다음과 같은 것이 있다.

The so-called GC (Garbage Collector) roots are objects special for garbage collector. Garbage collector collects those objects that are not GC roots and are not accessible by references from GC roots.

There are several kinds of GC roots. One object can belong to more than one kind of root. The root kinds are:

- Class - class loaded by system class loader. Such classes can never be unloaded. They can hold objects via static fields. Please note that classes loaded by custom class loaders are not roots, unless corresponding instances of java.lang.Class happen to be roots of other kind(s).
- Thread - live thread
- Stack Local - local variable or parameter of Java method
- JNI Local - local variable or parameter of JNI method
- JNI Global - global JNI reference
- Monitor Used - objects used as a monitor for synchronization
- Held by JVM - objects held from garbage collection by JVM for its purposes. Actually the list of such objects depends on JVM implementation. Possible known cases are: the system class loader, a few important exception classes which the JVM knows about, a few pre-allocated objects for exception handling, and custom class loaders when they are in the process of loading classes. Unfortunately, JVM provides absolutely no additional detail for such objects. Thus it is up to the analyst to decide to which case a certain "Held by JVM" belongs.

Tuesday, July 12, 2016

Android RenderScript mono filter 예제

// mono.rs
#pragma version(1)
#pragma rs java_package_name(com.example.renderscriptsample)

float3 gMonoMult = {0.2125, 0.7154, 0.0721};

void root(const uchar4 *v_in, uchar4 *v_out) {
    float4 f4 = rsUnpackColor8888(*v_in);
    float3 mono = dot(f4.rgb, gMonoMult);
    *v_out = rsPackColorTo8888(mono);
}

MainActivity.java
package com.example.renderscriptsample;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.renderscript.Allocation;
import android.renderscript.RenderScript;
import android.view.Menu;
import android.widget.ImageView;

public class MainActivity extends Activity {
 // RenderScript
 private RenderScript mRS;
 private Allocation mInAllocation;
 private Allocation mOutAllocation;
 private ScriptC_mono mScript;

 private Bitmap loadBitmap(int resource) {
  final BitmapFactory.Options options = new BitmapFactory.Options();
  options.inPreferredConfig = Bitmap.Config.ARGB_8888;
  return BitmapFactory.decodeResource(getResources(), resource, options);
 }

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // bitmap load
  final Bitmap bm = loadBitmap(R.drawable.data);
  final Bitmap bmOut = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());

  // renderscript init
  mRS = RenderScript.create(this);
  mInAllocation = Allocation.createFromBitmap(mRS, bm, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
  mOutAllocation = Allocation.createFromBitmap(mRS, bm, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
  mScript = new ScriptC_mono(mRS, getResources(), R.raw.mono);

  // renderscript run
  mScript.forEach_root(mInAllocation, mOutAllocation);
  mOutAllocation.copyTo(bmOut);
 
  // set output bitmap
  final ImageView iv = (ImageView) findViewById(R.id.imageView1);
  iv.setImageBitmap(bmOut);

 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}

Android pixmaps 특징

EGL also supports rendering surfaces whose color buffers are stored in native pixmaps. Pixmaps differ from windows in that they are typically allocated in off- screen (non-visible) graphics or CPU memory. Pixmaps differ from pbuffers in that they do have an associated native pixmap and native pixmap type, and it may be possible to render to pixmaps using APIs other than client APIs .

EGL defines several types of drawing surfaces collectively referred to as EGLSurfaces. These includewindows, used for onscreen rendering; pbuffers, used for offscreen rendering; and pixmaps, used for offscreen rendering into buffers that may be accessed through native APIs. EGL windows and pixmaps are tied to native window system windows and pixmaps.

The main differences between pixmaps and windows are:
•An EGL implementation doesn't need to support pixmaps (the native windowing system might not have an equivalent concept)
•Pixmaps are typically single-buffered, whereas a window might be double- or triple-buffered.
•Pixmaps are offscreen surfaces (although offscreen windows might be possible as well)

Android RenderScript FilterScript 예제

FilterScript

  • Introduced in Android 4.2 (API Level 17), Filterscript defines a subset of Renderscript that focuses on image processing operations, such as those that you would typically write with an OpenGL ES fragment shader.
  • 현재 android developer의 renderscript 항목에는 기본적으로 filterscript를 사용하기를 설명하고 있다.
    • http://developer.android.com/guide/topics/renderscript/compute.html
Usage
  • Inputs and return values of root functions cannot contain pointers. The default root function signature contains pointers, so you must use the __attribute__((kernel)) attribute to declare a custom root function when using Filterscript.
  • Built-in types cannot exceed 32-bits.
  • Filterscript must always use relaxed floating point precision by using the rs_fp_relaxed pragma.
    • Most applications can use rs_fp_relaxed without any side effects. This may be very beneficial on some architectures due to additional optimizations only available with relaxed precision (such as SIMD CPU instructions).
  • Filterscript files must end with an .fs extension, instead of an .rs extension
    • Android-18에서는 fs대신에 rs를 써도 된다.

//mono.fs
#pragma version(1)
#pragma rs java_package_name(com.example.renderscriptsample)
#pragma rs_fp_relaxed
// for version 17
// can called by forEach_invert(in, out)
uchar4 __attribute__((kernel)) invert(uchar4 in, uint32_t x, uint32_t y) {
  uchar4 out = in;
  out.r = 255 - in.r;
  out.g = 255 - in.g;
  out.b = 255 - in.b;
  return out;
}


//MainActivity.java
// renderscript init
mRS = RenderScript.create(this);
mInAllocation = Allocation.createFromBitmap(mRS, bm, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
mOutAllocation = Allocation.createFromBitmap(mRS, bm, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
mScript = new ScriptC_mono(mRS, getResources(), R.raw.mono);
// renderscript run
mScript.forEach_invert(mInAllocation, mOutAllocation);

Saturday, July 9, 2016

Android compileReleaseNdk 에러 해결

NDK를 사용할때 JNI라는 폴더가 있으면 다음과 같이 최신의 experimental plugin을 사용하라고 에러메세지가 뜬다.

Error:Execution failed for task ':imagefilter:compileReleaseNdk'.
> Error: NDK integration is deprecated in the current plugin.  Consider trying the new experimental plugin.  For details, see http://tools.android.com/tech-docs/new-build-system/gradle-experimental.  Set "android.useDeprecatedNdk=true" in gradle.properties to continue using the current NDK integration.

그럴때는 gradle에서 다음과 같이 선언하면 jni폴더를 무시하게 되고, 에러가 발생하지 않으며, 콘솔에서 ndk-build로 빌드할 수가 있다.

    sourceSets {
        main {
            // eclipse의 폴더명과 동일하게 사용함, 왜냐면 기본적으로 ndk-build의 결과는 libs안에 들어가게 된다.
            jniLibs.srcDirs = ["src/main/libs"]

            // android studio가 직접 컴파일하지 않게 함
            jni.srcDirs = []
        }
    }

Tuesday, July 5, 2016

Build 2016 요약 정리


  • 2.7억개 장치에서 윈도우10 가동
  • 펜 및 잉크 지원 향상
  • 윈도우10 Bash 지원
  • 코타나 향상 - XboxOne 지원
  • 통합 스토어 윈도우10
  • Edge 생체 인증 지원
  • 페이스북 광고 플랫폼이 유니버설 윈도우 플랫폼으로 들어옴
  • 일반 XboxOne을 개발기기로 사용가
  • 데스크탑앱을 유니버설 앱으로 컨버팅 지원 - 나중에 에이지오브엠파이어2 HD버전과 위처3로 데모할 예정
  • Visual Studio 2015 Update 2 예정됨
  • 모든 게임이 윈도우10과 Xbox One에 릴리즈 예정
  • 홀로렌즈 개발자킷이 공개됨
  • 주위의 사람들을 인식할수 있는 새로운 스마트폰 앱이 공개됨
  • CaptionBot이라는 사진인식 AI가 공개됨

iOS WWDC 2016 요약 정리


watchOS3
백그라운드 로딩속도 향상
글자인식
긴급상황+위치정보 전송
휠체어 운동량
미키마우스 인터페이스 변경


iOS10
손으로 들었을때 자동으로 켜짐
홈버튼 눌러서 잠금해제로 변경
잠금상태에서 3D터치로 메세지전송,사진촬영등 가능
제어센터 좌우 슬라이드
시리 써드파티 개방
사진 촬영장소, 얼굴인식 분류 가능
스마트홈앱
전화 스팸여부 확인, 써드파티 VoIP와 연결
메세지 업그레이드 - 손글씨, 전체화면, 이모티콘 변환
아이메세지 특수효과

Friday, July 1, 2016

iOS Swift 키보드 show/hide 시 UI 위치 보정 처리

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        registerForKeyboardNotifications()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        unregisterForKeyboardNotifications()
    }

    //MARK: Keyboard events
    func registerForKeyboardNotifications() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillShow), name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillHide), name: UIKeyboardWillHideNotification, object: nil)
    }

    func unregisterForKeyboardNotifications() {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
    }
    
    func keyboardWillShow(note: NSNotification) {
        // UI 키보드 위로 올려준다
        print("keyboardWillShow")

        let s = note.userInfo![UIKeyboardFrameEndUserInfoKey]
        let rect = s!.CGRectValue()
        
        // 입력창 위치를 올려줌
        var frame = textField.frame
        frame.origin.y -= rect.height
        textField.frame = frame

        let keyboardFrameEnd = view!.convertRect(rect, toView: nil)
        view.frame = CGRectMake(0, 0, keyboardFrameEnd.size.width, keyboardFrameEnd.origin.y)
        view.layoutIfNeeded()
    }
    
    func keyboardWillHide(note: NSNotification) {
        // UI 원위치 한다
        print("keyboardWillHide")

        let s = note.userInfo![UIKeyboardFrameBeginUserInfoKey]
        let rect = s!.CGRectValue()

        var frame = textField.frame
        frame.origin.y += rect.height
        textField.frame = frame
        
        frame = view.frame
        view.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.width, frame.height + rect.height)
        view.layoutIfNeeded()
    }