YuvDisplayer.h 5.9 KB
Newer Older
xiongziliang committed
1
/*
xiongziliang committed
2
 * MIT License
xzl committed
3
 *
xiongziliang committed
4
 * Copyright (c) 2017 xiongziliang <771730766@qq.com>
xiongziliang committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
xzl committed
23 24 25 26 27 28 29 30
 */
#ifndef YUVDISPLAYER_H_
#define YUVDISPLAYER_H_
#include <stdexcept>
#include "Util/onceToken.h"
#ifdef __cplusplus
extern "C" {
#endif
xiongziliang committed
31 32
#include "SDL2/SDL.h"
#include "libavcodec/avcodec.h"
xzl committed
33 34 35 36
#ifdef __cplusplus
}
#endif

xiongziliang committed
37 38 39 40
#if defined(_WIN32)
#pragma comment(lib,"SDL2.lib")
#endif //defined(_WIN32)

xiongziliang committed
41 42
using namespace toolkit;
using namespace mediakit;
xiongziliang committed
43 44 45

#define REFRESH_EVENT   (SDL_USEREVENT + 1)

46 47

#ifndef __MACH__
xiongziliang committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
class SDLDisplayerHelper
{
public:
    static SDLDisplayerHelper &Instance(){
        static SDLDisplayerHelper *instance(new SDLDisplayerHelper);
        return *instance;
    }
    static void Destory(){
        delete &Instance();
    }
    template<typename FUN>
    void doTask(FUN &&f){
        {
            lock_guard<mutex> lck(_mtxTask);
            _taskList.emplace_back(f);
        }
        SDL_Event event;
        event.type = REFRESH_EVENT;
        SDL_PushEvent(&event);
    }


private:
    SDLDisplayerHelper(){
        _loopThread.reset(new std::thread(&SDLDisplayerHelper::runLoop,this));
    };
    ~SDLDisplayerHelper(){
        doTask([](){return false;});
        _loopThread->join();
        _loopThread.reset();
    };

    void runLoop(){
        bool flag = true;
        std::function<bool ()> task;
        SDL_Event event;
        while(flag){
            SDL_WaitEvent(&event);
            if (event.type == REFRESH_EVENT)
            {
                {
                    lock_guard<mutex> lck(_mtxTask);
                    if(_taskList.empty()){
                        //not reachable
                        continue;
                    }
                    task = _taskList.front();
                    _taskList.pop_front();
                }
                flag = task();
            }

        }
    }


    std::deque<std::function<bool ()> > _taskList;
    std::shared_ptr<thread> _loopThread;
    std::mutex _mtxTask;

};
xzl committed
109

110 111
#endif //__MACH__

xzl committed
112 113
class YuvDisplayer {
public:
xiongziliang committed
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
	YuvDisplayer(void *hwnd = nullptr,const char *title = "untitled"){

        static onceToken token([]() {
            if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) == -1) {
                string err = "初始化SDL失败:";
                err+= SDL_GetError();
                ErrorL << err;
                throw std::runtime_error(err);
            }
            SDL_LogSetAllPriority(SDL_LOG_PRIORITY_CRITICAL);
            SDL_LogSetOutputFunction([](void *userdata, int category, SDL_LogPriority priority, const char *message){
                DebugL << category << " " <<  priority << message;
            },nullptr);
            InfoL << "SDL_Init";
        }, []() {
129
#ifndef __MACH__
xiongziliang committed
130
            SDLDisplayerHelper::Destory();
131
#endif
xiongziliang committed
132 133 134 135 136
            SDL_Quit();
        });

		_title = title;
		_hwnd = hwnd;
xzl committed
137 138
	}
	virtual ~YuvDisplayer(){
xiongziliang committed
139 140 141 142 143 144 145 146 147 148 149
		if (_texture) {
			SDL_DestroyTexture(_texture);
			_texture = nullptr;
		}
		if (_render) {
			SDL_DestroyRenderer(_render);
			_render = nullptr;
		}
		if (_win) {
			SDL_DestroyWindow(_win);
			_win = nullptr;
xzl committed
150 151 152
		}
	}
	bool displayYUV(AVFrame *pFrame){
xiongziliang committed
153 154 155 156 157 158 159 160 161 162 163
		if (!_win) {
			if (_hwnd) {
				_win = SDL_CreateWindowFrom(_hwnd);
			}else {
				_win = SDL_CreateWindow(_title.data(),
										SDL_WINDOWPOS_UNDEFINED,
										SDL_WINDOWPOS_UNDEFINED,
										pFrame->width,
										pFrame->height,
										SDL_WINDOW_OPENGL);
			}
xzl committed
164
		}
xiongziliang committed
165 166 167 168 169 170 171 172 173 174
		if (_win && ! _render){
#if 0
			SDL_RENDERER_SOFTWARE = 0x00000001,         /**< The renderer is a software fallback */
                    SDL_RENDERER_ACCELERATED = 0x00000002,      /**< The renderer uses hardware
                                                                     acceleration */
                    SDL_RENDERER_PRESENTVSYNC = 0x00000004,     /**< Present is synchronized
                                                                     with the refresh rate */
                    SDL_RENDERER_TARGETTEXTURE = 0x00000008     /**< The renderer supports
                                                                     rendering to texture */
#endif
xiongziliang committed
175

xiongziliang committed
176
			_render = SDL_CreateRenderer(_win, -1, SDL_RENDERER_ACCELERATED);
xzl committed
177
		}
xiongziliang committed
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
		if (_render && !_texture) {
			_texture = SDL_CreateTexture(_render, SDL_PIXELFORMAT_IYUV,
										 SDL_TEXTUREACCESS_STREAMING,
										 pFrame->width,
										 pFrame->height);
		}
		if (_texture) {
			SDL_UpdateYUVTexture(_texture, nullptr,
								 pFrame->data[0], pFrame->linesize[0],
								 pFrame->data[1], pFrame->linesize[1],
								 pFrame->data[2], pFrame->linesize[2]);

			//SDL_UpdateTexture(_texture, nullptr, pFrame->data[0], pFrame->linesize[0]);
			SDL_RenderClear(_render);
			SDL_RenderCopy(_render, _texture, nullptr, nullptr);
			SDL_RenderPresent(_render);
xzl committed
194 195 196 197 198
			return true;
		}
		return false;
	}
private:
xiongziliang committed
199 200 201 202 203
	string _title;
	SDL_Window *_win = nullptr;
	SDL_Renderer *_render = nullptr;
	SDL_Texture *_texture = nullptr;
	void *_hwnd = nullptr;
xzl committed
204 205
};

xiongziliang committed
206
#endif /* YUVDISPLAYER_H_ */