Pageviews

Wednesday, July 22, 2015

unique_ptr vs shared_ptr (weak_ptr) vs auto_ptr

unique_ptr

In C++, a smart pointer is implemented as a template class that mimics, by means of operator overloading, the behaviors of a traditional (raw) pointer, (e.g. dereferencing, assignment) while providing additional memory management features.
Smart pointers can facilitate intentional programming by expressing in the type itself how the memory of the referent of the pointer will be managed. For example, if a C++ function returns a pointer, there is no way to know whether the caller should delete the memory of the referent when the caller is finished with the information.
some_type* ambiguous_function(); // What should be done with the result?
Traditionally, comments have been used to resolve the ambiguity[citation needed], which is an error-prone, labor-intensive approach. C++11 introduced a way to ensure correct memory management in this case by declaring the function to return a unique_ptr,
unique_ptr<some_type> obvious_function1();
The declaration of the function return type as a unique_ptr makes explicit the fact that the caller takes ownership of the result, and the C++ runtime ensures that the memory for *some_type will be reclaimed automatically. Prior toC++11, unique_ptr can be replaced with auto_ptr.
Example: unique_ptr can only be transferred not copied.
std::unique_ptr<int> p1(new int(5));
std::unique_ptr<int> p2 = p1; //Compile error.
std::unique_ptr<int> p3 = std::move(p1); //Transfers ownership. p3 now owns the memory and p1 is rendered invalid.

p3.reset(); //Deletes the memory.
p1.reset(); //Does nothing.

shared_ptr (weak_ptr)
shared_ptr is a container for a raw pointer. It maintains reference-counted ownership of its contained pointer in cooperation with all copies of the shared_ptr. The object referenced by the contained raw pointer will be destroyed when and only when all copies of the shared_ptr have been destroyed.
std::shared_ptr<int> p1(new int(5));
std::shared_ptr<int> p2 = p1; //Both now own the memory.

p1.reset(); //Memory still exists, due to p2.
p2.reset(); //Deletes the memory, since no one else owns the memory.
weak_ptr is a container for a raw pointer. It is created as a copy of a shared_ptr. The existence or destruction of weak_ptr copies of a shared_ptr have no effect on the shared_ptr or its other copies. After all copies of a shared_ptr have been destroyed, all weak_ptr copies become empty.
Because the implementation of shared_ptr uses reference countingcircular references are potentially a problem. A circular shared_ptr chain can be broken by changing the code so that one of the references is aweak_ptr.
Multiple threads can safely simultaneously access different shared_ptr and weak_ptr objects that point to the same object.[4]
The referenced object itself needs to be protected separately to ensure thread safety.

auto_ptr 
Create new objects using auto_ptr to ease the allocation of a
std::shared_ptr<some_type>
C++11 introduced:
 auto s = std::make_shared<some_type>(constructor, parameters, here);
and similarly
std::unique_ptr<some_type>
Since C++14 one can use:
 auto u = std::make_unique<some_type>(constructor, parameters, here);
It is preferred, in almost all circumstances, to use these facilities over the new keyword:[1]

stdcall vs cdecl

The _stdcall calling convention is a variation on the Pascal calling convention in which the callee is responsible for cleaning up the stack, so the compiler makes vararg functions__cdecl. 
stdcall is the standard calling convention for the Microsoft Win32 API and for Open Watcom C++.
Element
Implementation
Argument-passing order
Right to left.
Argument-passing convention
By value, unless a pointer or reference type is passed.
Stack-maintenance responsibility
Callee pops its own arguments from the stack.
Name-decoration convention
An underscore (_) is prefixed to the name. The name is followed 
by the at sign (@) followed by the number of bytes (in decimal) 
in the argument list. Therefore, the function declared as
int func( int a, double b ) is decorated as follows: _func@12
Case-translation convention
No case translation performed.

The _cdecl calling convention is the default calling convention for C and C++ programs. Because the stack is cleaned up by the caller, it can do vararg functions.  Registers EAX, ECX, and EDX are designated for use within the function. Return values are stored in the EAX register.
Element
Implementation
Argument-passing order
Right to left.
Stack-maintenance responsibility
Caller pops the arguments from the stack.
Name-decoration convention
Underscore character (_) is prefixed to names, except 
when __cdecl functions that use C linkage are exported.
Case-translation convention
No case translation performed.
Subtle differences
The __cdecl calling convention creates larger executables than __stdcall, because it requires each function call to include stack cleanup code.

Tuesday, November 25, 2014

UML - Class Diagram - C++

1. Class representation
    • Visibility: public "+" / private "-"
    • Parameter direction: input "in" / in&out "inout" / output param "out"
    • Type of members: static method is underlined / pure virtual function italics
2. Class relationship
    • Association         ------------>
      • maybe aggregation
      • maybe composition
      • maybe dependency
    • Dependency        - - - - - - ->
      • class X { void foo(Y y){}; }
      • A dependency is very much implied by an association.
    • Aggregation        <>--------->
      • X weakly contains Y
      • class X { Y* y; }
    • Composition       <+>------->
      • X strongly contains Y
      • class X { Y y; }
    • Generalization    ------------|>
      • inheritance
    • Class template    
      • two class representation overlay
      • generic programming
    • Multiplicity in a relationship
      • "0..1" none or one
      • "1"     exactly one
      • "*"     zero or more
      • "1..*" at least one

Tuesday, November 18, 2014

All Around Topics for C++ Users

This post is written based on a popular programming website.

1, Variables
  • local vs global vs Constants
2, Operators
  • Scope resolution ::, sizeof
  • Member access   ".", "->"
  • Bitwise                &, |, ^, ~, >>, <<
  • Conditional         ?, :
  • Operator Precedence
3, Control Structures
  • if else
  • return
  • goto
  • exit
  • break
  • continue
4, Arrays
  • pass array as parameters - int sum(int[]);
  • array of strings - char weekend[2] [9] = {"Sunday", "Saturday" };
  • array of objects - objects are user defined data type
5, Functions
  • pass by value
  • pass by reference
6, Class
  • Access specifiers - private, public, protected
  • Friend function - have access to private/protected members of a class, a bridge between classes.
  • Constructors
  • Default Constructors - no parameters or all of default values.
  • Overloading Constructors - increase flexibility of a class by having more constructors.
  • Destructors
  • Nested classes - Not given importance because of the inheritance.
  • Local classes - a class defined inside a function.
7, Predefined Functions
  • I/O Functions - scanf, vsprintf, fread, setbuf
  • String & Character Functions - strcpy, strlen, memset 
  • Mathematical Functions - cos, floor, sin, sqrt
  • Time, Data & Localization Functions - asctime, localtime, strftime
  • Dynamic Allocation Functions - calloc, free, malloc, realloc
  • Utility Functions - abort, bsearch, qsort, rand, exit
8, Object Oriented Programming (OOPS)
  • Object oriented analysis (OOA) - specify real world requirements, behaviour & interactions.
  • Object oriented design (OOD) - convert analysis into a hierarchy of objects.
  • Object oriented programming (OOP) - implement objects using C++.
9, OOPS
  • Objects - instance of a class that interact with each other at runtime.
  • Classes - data members + member functions
  • Inheritance - visibility of base and derived class members.
  • Dynamic Binding - aka "late binding", "runtime binding"
  • Polymorphism
  • Message passing - ?
  • Encapsulation
10, Inheritance Con't
  • Single inheritance
  • Multiple inheritance - a class is derived from more than one base class.
  • Hierarchical inheritance - two or more classes are inherited from a single class.
  • Multilevel inheritance - a derived class is derived from another derived class.
  • Hybrid inheritance - one or more types of inheritance are combined.
  • Virtual inheritance - solve "diamond problem".
11, Polymorphism Con't
  • Compile time polymorphism - aka "function overloading" that depends on the arguments. 
  • Run time polymorphism - late binding by using virtual function to override in derived class.
12, Encapsulation Con't
  • Data abstraction - using data without knowing how its stored.
  • Function abstraction - using function without knowing how its implemented.
13, Type Casting
  • static_cast - convert a base class pointers to the derived class, vice versa.
  • reinterpret_cast - convert a pointer of one type to another unrelated type.
  • const_cast - add or remove a "const" modifier from a type. 
  • dynamic_cast - used with pointers and objects to do casting at runtime. [RTTI]
  • typeid - determine the class (ex, typeid(pA).name()) of an object at runtime. [RTTI]
14, Forward declaration
  • can only use the pointer-to-that-class type. 
  • avoid circular references. 
  • not sufficient if you need to use the actual class type. (base class or use member functions)
*********************************************************************************
Special Topics

Pointers - declare as TYPE *NAME
  • reference operator - "&"
  • dereference operator - "*" or "->"
Structures
  • By default, all members of a struct are "public", members in function of a struct are "private".
Unions
  • At at instance it contains only a single object.
Enumerations
  • create new data types that can take on only a restricted range of values.
typedef
  • used to make the code more portable, easy to change data type.
comments
  • // 
  • /**/
Function overloading 
  • Define multiple function with the same name but perform different tasks based on the number, type of arguments of that function. @compile time.
Operator overloading
  • Define additional task to an operator in reference to a class.
  • Cannot overload: member access operator, scope resolution operator, conditional operator. 
Virtual functions
  • executes based on the type of object pointed by the base pointer at runtime and not on the type of pointer.
Exception handling
  • "try", "throw", "catch"
  • try{ if(1/r)else{throw(r)} } catch(int r) { ... }
Namespace
  • a new concept introduced by the ANSI C++ standards committee.
  • namespace namespace_name{ //declaration of var, func, classes, etc. }

Monday, November 17, 2014

Object Oriented Programming Concepts in C++

1, Coding structures
  • templates < inheritance < composition in terms of better usage frequency.
2, Helper class
  • as a static - does not keep state of the class instance.
  • as a singleton - keep a universal state of a single class instance.
  • as a base class - distinct states and fine-grain control of accessibility to its helper functions.  
3, Namespace
  • Preventing redefinition of user-defined keyboards.
  • A C++ framework should have at least one namespace to group all files. 
  • Compiler just add this constant string as prefix of variables.
4, Forward declarations
  • Only used as pointer types.
  • Behaving like void* but no need to cast.
5, Virtual inheritance 
  • To solve ambiguous hierarchy composition (known as the "diamond problem")
  • A particular base class in an inheritance hierarchy is declared to share its member data instances with any other inclusions of that same base in further derived classes.
6, Class ID Macro
  • AMF_DECLARE_IID("AMFCFilter")
  • Macro methods for getting current class name for debugging.
7, x86 calling conventions
  • Caller clean-up: cdecl syscall optlink
  • Callee clean-up: stdcall fastcall register // AMF_STD_CALL informs compiler how to call.
8, Pure virtual functions
  • It overwrites this method pointer in class instance memory to point to a warning methods. The program terminates if the pointer is not overwritten and output warning.
  • Basically pure virtual functions are required to be implemented in sub classes.
9, Virtual functions

  • Able to calling the corresponding virtual methods based on class instance memory instead of static pointer type.
  • If B is a subclass of A: A* pA = new B(); pA->foo(); => invokes B's foo().
10, Call base class' overwritten methods from subclass.
  • base_class::foo(...)
  • Unlike Java/C#: C++ does not have super or base keywords due to support of multiple inheritance.
11, String
  • wchar_t:  2 bytes per char unicode - support minimum Chinese, Korean, etc.
  • ANSI:     1 byte per char
12, Single/ Double/ Triple, etc. pointers
  • A *pA - dereference 1 time to get value.
  • A **pA - dereference 2 times to get value.
  • A ****pA - dereference 4 times to get value.
13, Synonyms
  • int i = 0; int &j = i; compiler will replace j with i during compilation.
  • Compare to pointer, reference could control size of an array. foo(int[4] &pA);
14, static_cast vs reinterpret_cast vs const_cast vs dynamic_cast
  • static_cast is a strict explicit casting. (Make sure casting fine at compile time.)
  • reinterpret_cast is a loose explicit C style casting. (You know what you doing or it fails.)
  • const_cast converts const variable to be non-const variable. (Should not use unless its a hack.)
  • dynamic_cast is the same as static_cast at compile time, but it also checks at runtime. (Never used)
15, Include guards
  • #ifndef #define #endif - C style
  • #pragma once - C++ style
16, Operator overloading
  • TYPE& operator=() 
  • Only the above function signature matches then the overloaded methods is called.
17, Constructors vs Copy Constructors vs ...

Thursday, August 14, 2014

FFMpeg Useful Commands. [Constantly Updating]


FFMpeg Useful Commands. [Constantly Updating]



FFMpeg is primarily a transcoder. It supports practically all audio/video codecs/containers as well as elementary stream formats in the market. It provides a host of audio filters (eg: resampling, downmix channels) and video filters (eg: crop, pad, etc) to use during transcoding.


First:

ffmpeg -h



1, To convert a regular mp4 video into raw videos, such as a .yuv file.

ffmpeg -i ABC.mp4 ABC.yuv


2, To find out supported pixel formats.

ffmpeg -pix_fmts


3, To Convert a 720x480 nv12 (yuv 420 semi-planar) image to png

ffmpeg -s 176X144 -pix_fmt nv12 -i ABC.yuv -f image2 -pix_fmt rgb24 ABC.png





4, To cut the clip for certain duration[HH:MM:SS.xxx]


ffmpeg -i ABC.wmv -ss 01:01:30.0 -c copy -t 00:00:01.0 ABCout.wmv


ffmpeg -i ABC.wmv -ss 30 -c copy -t 10 ABCout.wmv



5, To convert an YUV file to BMP


ffmpeg -s 144x176 -pix_fmt yuv420p -i ABC.yuv ABC.bmp

ffmpeg -s 320x240 -pix_fmt nv12 -i ABC_nv12.yuv -s 320x240 -pix_fmt yuv420p ABC_yuv420p.yuv






6, Extracting YUV:

ffmpeg -i <inputFile> -vcodec rawvideo <output.yuv>


7, Resizing YUV:

ffmpeg -s 320x240 -i <input_320x240.yuv> -s 640x480 <output_640x480.yuv>






8, Controlling number of frames to process:

ffmpeg -vframes 100 <inputInfo> -i <inputFile> <encodeOptions> <outputFile>






Note:


-t is an output option and always needs to be specified after -i.


-to instead of -t to specify the timestamp to which you want to cut.

-ss after -i, you get more accurate seeking at the expense of a slower execution altogether.

See also: Seeking with FFmpeg – FFmpeg


List of supported containers:

ffmpeg -formats


List of supported codecs:

ffmpeg -codecs


Get codec information for a file:

ffmpeg -i <inputFile>






List of supported pixel formats:

ffmpeg -pix_fmts


Giving start offsets while processing:

ffmpeg -ss HH:MM:SS -i <input> -vcodec copy <output>

"-ss" sets offset in seconds.

"-r <val>" can be used to change the fps.


Extracting elementary streams:Identify required elementary stream format from supported formats using: ffmpeg -formats






To extract:

ffmpeg -i <input> -vcodec copy -f <format> <output.format>


Example 1: Extracting elementary H.264 from an AVI



ffmpeg -formats gives "format = h264"

ffmpeg -i input.avi -vcodec copy -vbsf h264_mp4toannexb -f h264 output.h264


Example 2: Extracting elementary MPEG4 from an AVI


ffmpeg -formats gives "format = m4v"

ffmpeg -i input.avi -vcodec copy -f m4v output.m4v


Get bmp/png/jpg for frames:

ffmpeg -ss 00:10:00 -vframes 10 -i <inputFile> output.bmp

This will dump bitmaps for ten frames from the time stamp 00:10:00 into files name output01.bmp, output02.bmp and so on....


You can get .png, .jpg, .gif similarly.

Note that lossy codecs like jpeg will involve re-encoding and loss in quality. You can add "qmax=10" or any appropriate value to control the quality.

Hack: To handle raw YUV similarly, rename all yuv to bmp. Specify -vcodec rawvideo, -s wxh and -pix_fmt yuv420p before -i filename.


Filters:

The following applies to all codecs/YUVs/elementary streams/containers as long as the resultant data is supported by the same.



Video Cropping:

Newer versions:

ffmpeg -i input_320x240.avi -vf crop=<w>:<h>:<x>:<y> output_300x220.avi

w = Output width

h = Output height

x = X co-ordinate of output image in the input image

y = Y co-ordinate of output image in the input image

Video Padding:

<RRGGBB[AA]> is in HEX. FF0000 = RED, 0000FF = BLUE, etc...

Newer versions:

ffmpeg -i input_320x240.avi -vf pad=<w>:<h>:<x>:<y>:<c> output_340x260.avi

w = Output width

h = Output height

x = X co-ordinate of input image in the output image

y = Y co-ordinate of input image in the output image

c = Padding color in <RRGGBB[AA]> format. FF0000 = RED, 0000FF = BLUE, etc...

Also see Encoding using FFMpeg