You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

948 lines
37KB

  1. /*
  2. * OMX Video encoder
  3. * Copyright (C) 2011 Martin Storsjo
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "config.h"
  22. #if CONFIG_OMX_RPI
  23. #define OMX_SKIP64BIT
  24. #endif
  25. #include <dlfcn.h>
  26. #include <OMX_Core.h>
  27. #include <OMX_Component.h>
  28. #include <pthread.h>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <sys/time.h>
  32. #include "libavutil/avstring.h"
  33. #include "libavutil/avutil.h"
  34. #include "libavutil/common.h"
  35. #include "libavutil/imgutils.h"
  36. #include "libavutil/log.h"
  37. #include "libavutil/opt.h"
  38. #include "avcodec.h"
  39. #include "h264.h"
  40. #include "internal.h"
  41. #ifdef OMX_SKIP64BIT
  42. static OMX_TICKS to_omx_ticks(int64_t value)
  43. {
  44. OMX_TICKS s;
  45. s.nLowPart = value & 0xffffffff;
  46. s.nHighPart = value >> 32;
  47. return s;
  48. }
  49. static int64_t from_omx_ticks(OMX_TICKS value)
  50. {
  51. return (((int64_t)value.nHighPart) << 32) | value.nLowPart;
  52. }
  53. #else
  54. #define to_omx_ticks(x) (x)
  55. #define from_omx_ticks(x) (x)
  56. #endif
  57. #define INIT_STRUCT(x) do { \
  58. x.nSize = sizeof(x); \
  59. x.nVersion = s->version; \
  60. } while (0)
  61. #define CHECK(x) do { \
  62. if (x != OMX_ErrorNone) { \
  63. av_log(avctx, AV_LOG_ERROR, \
  64. "err %x (%d) on line %d\n", x, x, __LINE__); \
  65. return AVERROR_UNKNOWN; \
  66. } \
  67. } while (0)
  68. typedef struct OMXContext {
  69. void *lib;
  70. void *lib2;
  71. OMX_ERRORTYPE (*ptr_Init)(void);
  72. OMX_ERRORTYPE (*ptr_Deinit)(void);
  73. OMX_ERRORTYPE (*ptr_ComponentNameEnum)(OMX_STRING, OMX_U32, OMX_U32);
  74. OMX_ERRORTYPE (*ptr_GetHandle)(OMX_HANDLETYPE*, OMX_STRING, OMX_PTR, OMX_CALLBACKTYPE*);
  75. OMX_ERRORTYPE (*ptr_FreeHandle)(OMX_HANDLETYPE);
  76. OMX_ERRORTYPE (*ptr_GetComponentsOfRole)(OMX_STRING, OMX_U32*, OMX_U8**);
  77. OMX_ERRORTYPE (*ptr_GetRolesOfComponent)(OMX_STRING, OMX_U32*, OMX_U8**);
  78. void (*host_init)(void);
  79. } OMXContext;
  80. static av_cold void *dlsym_prefixed(void *handle, const char *symbol, const char *prefix)
  81. {
  82. char buf[50];
  83. snprintf(buf, sizeof(buf), "%s%s", prefix ? prefix : "", symbol);
  84. return dlsym(handle, buf);
  85. }
  86. static av_cold int omx_try_load(OMXContext *s, void *logctx,
  87. const char *libname, const char *prefix,
  88. const char *libname2)
  89. {
  90. if (libname2) {
  91. s->lib2 = dlopen(libname2, RTLD_NOW | RTLD_GLOBAL);
  92. if (!s->lib2) {
  93. av_log(logctx, AV_LOG_WARNING, "%s not found\n", libname);
  94. return AVERROR_ENCODER_NOT_FOUND;
  95. }
  96. s->host_init = dlsym(s->lib2, "bcm_host_init");
  97. if (!s->host_init) {
  98. av_log(logctx, AV_LOG_WARNING, "bcm_host_init not found\n");
  99. dlclose(s->lib2);
  100. s->lib2 = NULL;
  101. return AVERROR_ENCODER_NOT_FOUND;
  102. }
  103. }
  104. s->lib = dlopen(libname, RTLD_NOW | RTLD_GLOBAL);
  105. if (!s->lib) {
  106. av_log(logctx, AV_LOG_WARNING, "%s not found\n", libname);
  107. return AVERROR_ENCODER_NOT_FOUND;
  108. }
  109. s->ptr_Init = dlsym_prefixed(s->lib, "OMX_Init", prefix);
  110. s->ptr_Deinit = dlsym_prefixed(s->lib, "OMX_Deinit", prefix);
  111. s->ptr_ComponentNameEnum = dlsym_prefixed(s->lib, "OMX_ComponentNameEnum", prefix);
  112. s->ptr_GetHandle = dlsym_prefixed(s->lib, "OMX_GetHandle", prefix);
  113. s->ptr_FreeHandle = dlsym_prefixed(s->lib, "OMX_FreeHandle", prefix);
  114. s->ptr_GetComponentsOfRole = dlsym_prefixed(s->lib, "OMX_GetComponentsOfRole", prefix);
  115. s->ptr_GetRolesOfComponent = dlsym_prefixed(s->lib, "OMX_GetRolesOfComponent", prefix);
  116. if (!s->ptr_Init || !s->ptr_Deinit || !s->ptr_ComponentNameEnum ||
  117. !s->ptr_GetHandle || !s->ptr_FreeHandle ||
  118. !s->ptr_GetComponentsOfRole || !s->ptr_GetRolesOfComponent) {
  119. av_log(logctx, AV_LOG_WARNING, "Not all functions found in %s\n", libname);
  120. dlclose(s->lib);
  121. s->lib = NULL;
  122. if (s->lib2)
  123. dlclose(s->lib2);
  124. s->lib2 = NULL;
  125. return AVERROR_ENCODER_NOT_FOUND;
  126. }
  127. return 0;
  128. }
  129. static av_cold OMXContext *omx_init(void *logctx, const char *libname, const char *prefix)
  130. {
  131. static const char * const libnames[] = {
  132. #if CONFIG_OMX_RPI
  133. "/opt/vc/lib/libopenmaxil.so", "/opt/vc/lib/libbcm_host.so",
  134. #else
  135. "libOMX_Core.so", NULL,
  136. "libOmxCore.so", NULL,
  137. #endif
  138. NULL
  139. };
  140. const char* const* nameptr;
  141. int ret = AVERROR_ENCODER_NOT_FOUND;
  142. OMXContext *omx_context;
  143. omx_context = av_mallocz(sizeof(*omx_context));
  144. if (!omx_context)
  145. return NULL;
  146. if (libname) {
  147. ret = omx_try_load(omx_context, logctx, libname, prefix, NULL);
  148. if (ret < 0) {
  149. av_free(omx_context);
  150. return NULL;
  151. }
  152. } else {
  153. for (nameptr = libnames; *nameptr; nameptr += 2)
  154. if (!(ret = omx_try_load(omx_context, logctx, nameptr[0], prefix, nameptr[1])))
  155. break;
  156. if (!*nameptr) {
  157. av_free(omx_context);
  158. return NULL;
  159. }
  160. }
  161. if (omx_context->host_init)
  162. omx_context->host_init();
  163. omx_context->ptr_Init();
  164. return omx_context;
  165. }
  166. static av_cold void omx_deinit(OMXContext *omx_context)
  167. {
  168. if (!omx_context)
  169. return;
  170. omx_context->ptr_Deinit();
  171. dlclose(omx_context->lib);
  172. av_free(omx_context);
  173. }
  174. typedef struct OMXCodecContext {
  175. const AVClass *class;
  176. char *libname;
  177. char *libprefix;
  178. OMXContext *omx_context;
  179. AVCodecContext *avctx;
  180. char component_name[OMX_MAX_STRINGNAME_SIZE];
  181. OMX_VERSIONTYPE version;
  182. OMX_HANDLETYPE handle;
  183. int in_port, out_port;
  184. OMX_COLOR_FORMATTYPE color_format;
  185. int stride, plane_size;
  186. int num_in_buffers, num_out_buffers;
  187. OMX_BUFFERHEADERTYPE **in_buffer_headers;
  188. OMX_BUFFERHEADERTYPE **out_buffer_headers;
  189. int num_free_in_buffers;
  190. OMX_BUFFERHEADERTYPE **free_in_buffers;
  191. int num_done_out_buffers;
  192. OMX_BUFFERHEADERTYPE **done_out_buffers;
  193. pthread_mutex_t input_mutex;
  194. pthread_cond_t input_cond;
  195. pthread_mutex_t output_mutex;
  196. pthread_cond_t output_cond;
  197. pthread_mutex_t state_mutex;
  198. pthread_cond_t state_cond;
  199. OMX_STATETYPE state;
  200. OMX_ERRORTYPE error;
  201. int mutex_cond_inited;
  202. int eos_sent, got_eos;
  203. uint8_t *output_buf;
  204. int output_buf_size;
  205. int input_zerocopy;
  206. } OMXCodecContext;
  207. static void append_buffer(pthread_mutex_t *mutex, pthread_cond_t *cond,
  208. int* array_size, OMX_BUFFERHEADERTYPE **array,
  209. OMX_BUFFERHEADERTYPE *buffer)
  210. {
  211. pthread_mutex_lock(mutex);
  212. array[(*array_size)++] = buffer;
  213. pthread_cond_broadcast(cond);
  214. pthread_mutex_unlock(mutex);
  215. }
  216. static OMX_BUFFERHEADERTYPE *get_buffer(pthread_mutex_t *mutex, pthread_cond_t *cond,
  217. int* array_size, OMX_BUFFERHEADERTYPE **array,
  218. int wait)
  219. {
  220. OMX_BUFFERHEADERTYPE *buffer;
  221. pthread_mutex_lock(mutex);
  222. if (wait) {
  223. while (!*array_size)
  224. pthread_cond_wait(cond, mutex);
  225. }
  226. if (*array_size > 0) {
  227. buffer = array[0];
  228. (*array_size)--;
  229. memmove(&array[0], &array[1], (*array_size) * sizeof(OMX_BUFFERHEADERTYPE*));
  230. } else {
  231. buffer = NULL;
  232. }
  233. pthread_mutex_unlock(mutex);
  234. return buffer;
  235. }
  236. static OMX_ERRORTYPE event_handler(OMX_HANDLETYPE component, OMX_PTR app_data, OMX_EVENTTYPE event,
  237. OMX_U32 data1, OMX_U32 data2, OMX_PTR event_data)
  238. {
  239. OMXCodecContext *s = app_data;
  240. // This uses casts in the printfs, since OMX_U32 actually is a typedef for
  241. // unsigned long in official header versions (but there are also modified
  242. // versions where it is something else).
  243. switch (event) {
  244. case OMX_EventError:
  245. pthread_mutex_lock(&s->state_mutex);
  246. av_log(s->avctx, AV_LOG_ERROR, "OMX error %"PRIx32"\n", (uint32_t) data1);
  247. s->error = data1;
  248. pthread_cond_broadcast(&s->state_cond);
  249. pthread_mutex_unlock(&s->state_mutex);
  250. break;
  251. case OMX_EventCmdComplete:
  252. if (data1 == OMX_CommandStateSet) {
  253. pthread_mutex_lock(&s->state_mutex);
  254. s->state = data2;
  255. av_log(s->avctx, AV_LOG_VERBOSE, "OMX state changed to %"PRIu32"\n", (uint32_t) data2);
  256. pthread_cond_broadcast(&s->state_cond);
  257. pthread_mutex_unlock(&s->state_mutex);
  258. } else if (data1 == OMX_CommandPortDisable) {
  259. av_log(s->avctx, AV_LOG_VERBOSE, "OMX port %"PRIu32" disabled\n", (uint32_t) data2);
  260. } else if (data1 == OMX_CommandPortEnable) {
  261. av_log(s->avctx, AV_LOG_VERBOSE, "OMX port %"PRIu32" enabled\n", (uint32_t) data2);
  262. } else {
  263. av_log(s->avctx, AV_LOG_VERBOSE, "OMX command complete, command %"PRIu32", value %"PRIu32"\n",
  264. (uint32_t) data1, (uint32_t) data2);
  265. }
  266. break;
  267. case OMX_EventPortSettingsChanged:
  268. av_log(s->avctx, AV_LOG_VERBOSE, "OMX port %"PRIu32" settings changed\n", (uint32_t) data1);
  269. break;
  270. default:
  271. av_log(s->avctx, AV_LOG_VERBOSE, "OMX event %d %"PRIx32" %"PRIx32"\n",
  272. event, (uint32_t) data1, (uint32_t) data2);
  273. break;
  274. }
  275. return OMX_ErrorNone;
  276. }
  277. static OMX_ERRORTYPE empty_buffer_done(OMX_HANDLETYPE component, OMX_PTR app_data,
  278. OMX_BUFFERHEADERTYPE *buffer)
  279. {
  280. OMXCodecContext *s = app_data;
  281. if (s->input_zerocopy) {
  282. if (buffer->pAppPrivate) {
  283. if (buffer->pOutputPortPrivate)
  284. av_free(buffer->pAppPrivate);
  285. else
  286. av_frame_free((AVFrame**)&buffer->pAppPrivate);
  287. buffer->pAppPrivate = NULL;
  288. }
  289. }
  290. append_buffer(&s->input_mutex, &s->input_cond,
  291. &s->num_free_in_buffers, s->free_in_buffers, buffer);
  292. return OMX_ErrorNone;
  293. }
  294. static OMX_ERRORTYPE fill_buffer_done(OMX_HANDLETYPE component, OMX_PTR app_data,
  295. OMX_BUFFERHEADERTYPE *buffer)
  296. {
  297. OMXCodecContext *s = app_data;
  298. append_buffer(&s->output_mutex, &s->output_cond,
  299. &s->num_done_out_buffers, s->done_out_buffers, buffer);
  300. return OMX_ErrorNone;
  301. }
  302. static const OMX_CALLBACKTYPE callbacks = {
  303. event_handler,
  304. empty_buffer_done,
  305. fill_buffer_done
  306. };
  307. static av_cold int find_component(OMXContext *omx_context, void *logctx,
  308. const char *role, char *str, int str_size)
  309. {
  310. OMX_U32 i, num = 0;
  311. char **components;
  312. int ret = 0;
  313. #if CONFIG_OMX_RPI
  314. if (av_strstart(role, "video_encoder.", NULL)) {
  315. av_strlcpy(str, "OMX.broadcom.video_encode", str_size);
  316. return 0;
  317. }
  318. #endif
  319. omx_context->ptr_GetComponentsOfRole((OMX_STRING) role, &num, NULL);
  320. if (!num) {
  321. av_log(logctx, AV_LOG_WARNING, "No component for role %s found\n", role);
  322. return AVERROR_ENCODER_NOT_FOUND;
  323. }
  324. components = av_mallocz_array(num, sizeof(*components));
  325. if (!components)
  326. return AVERROR(ENOMEM);
  327. for (i = 0; i < num; i++) {
  328. components[i] = av_mallocz(OMX_MAX_STRINGNAME_SIZE);
  329. if (!components[i]) {
  330. ret = AVERROR(ENOMEM);
  331. goto end;
  332. }
  333. }
  334. omx_context->ptr_GetComponentsOfRole((OMX_STRING) role, &num, (OMX_U8**) components);
  335. av_strlcpy(str, components[0], str_size);
  336. end:
  337. for (i = 0; i < num; i++)
  338. av_free(components[i]);
  339. av_free(components);
  340. return ret;
  341. }
  342. static av_cold int wait_for_state(OMXCodecContext *s, OMX_STATETYPE state)
  343. {
  344. int ret = 0;
  345. pthread_mutex_lock(&s->state_mutex);
  346. while (s->state != state && s->error == OMX_ErrorNone)
  347. pthread_cond_wait(&s->state_cond, &s->state_mutex);
  348. if (s->error != OMX_ErrorNone)
  349. ret = AVERROR_ENCODER_NOT_FOUND;
  350. pthread_mutex_unlock(&s->state_mutex);
  351. return ret;
  352. }
  353. static av_cold int omx_component_init(AVCodecContext *avctx, const char *role)
  354. {
  355. OMXCodecContext *s = avctx->priv_data;
  356. OMX_PARAM_COMPONENTROLETYPE role_params = { 0 };
  357. OMX_PORT_PARAM_TYPE video_port_params = { 0 };
  358. OMX_PARAM_PORTDEFINITIONTYPE in_port_params = { 0 }, out_port_params = { 0 };
  359. OMX_VIDEO_PARAM_PORTFORMATTYPE video_port_format = { 0 };
  360. OMX_VIDEO_PARAM_BITRATETYPE vid_param_bitrate = { 0 };
  361. OMX_ERRORTYPE err;
  362. int i;
  363. s->version.s.nVersionMajor = 1;
  364. s->version.s.nVersionMinor = 1;
  365. s->version.s.nRevision = 2;
  366. err = s->omx_context->ptr_GetHandle(&s->handle, s->component_name, s, (OMX_CALLBACKTYPE*) &callbacks);
  367. if (err != OMX_ErrorNone) {
  368. av_log(avctx, AV_LOG_ERROR, "OMX_GetHandle(%s) failed: %x\n", s->component_name, err);
  369. return AVERROR_UNKNOWN;
  370. }
  371. // This one crashes the mediaserver on qcom, if used over IOMX
  372. INIT_STRUCT(role_params);
  373. av_strlcpy(role_params.cRole, role, sizeof(role_params.cRole));
  374. // Intentionally ignore errors on this one
  375. OMX_SetParameter(s->handle, OMX_IndexParamStandardComponentRole, &role_params);
  376. INIT_STRUCT(video_port_params);
  377. err = OMX_GetParameter(s->handle, OMX_IndexParamVideoInit, &video_port_params);
  378. CHECK(err);
  379. s->in_port = s->out_port = -1;
  380. for (i = 0; i < video_port_params.nPorts; i++) {
  381. int port = video_port_params.nStartPortNumber + i;
  382. OMX_PARAM_PORTDEFINITIONTYPE port_params = { 0 };
  383. INIT_STRUCT(port_params);
  384. port_params.nPortIndex = port;
  385. err = OMX_GetParameter(s->handle, OMX_IndexParamPortDefinition, &port_params);
  386. if (err != OMX_ErrorNone) {
  387. av_log(avctx, AV_LOG_WARNING, "port %d error %x\n", port, err);
  388. break;
  389. }
  390. if (port_params.eDir == OMX_DirInput && s->in_port < 0) {
  391. in_port_params = port_params;
  392. s->in_port = port;
  393. } else if (port_params.eDir == OMX_DirOutput && s->out_port < 0) {
  394. out_port_params = port_params;
  395. s->out_port = port;
  396. }
  397. }
  398. if (s->in_port < 0 || s->out_port < 0) {
  399. av_log(avctx, AV_LOG_ERROR, "No in or out port found (in %d out %d)\n", s->in_port, s->out_port);
  400. return AVERROR_UNKNOWN;
  401. }
  402. s->color_format = 0;
  403. for (i = 0; ; i++) {
  404. INIT_STRUCT(video_port_format);
  405. video_port_format.nIndex = i;
  406. video_port_format.nPortIndex = s->in_port;
  407. if (OMX_GetParameter(s->handle, OMX_IndexParamVideoPortFormat, &video_port_format) != OMX_ErrorNone)
  408. break;
  409. if (video_port_format.eColorFormat == OMX_COLOR_FormatYUV420Planar ||
  410. video_port_format.eColorFormat == OMX_COLOR_FormatYUV420PackedPlanar) {
  411. s->color_format = video_port_format.eColorFormat;
  412. break;
  413. }
  414. }
  415. if (s->color_format == 0) {
  416. av_log(avctx, AV_LOG_ERROR, "No supported pixel formats (%d formats available)\n", i);
  417. return AVERROR_UNKNOWN;
  418. }
  419. in_port_params.bEnabled = OMX_TRUE;
  420. in_port_params.bPopulated = OMX_FALSE;
  421. in_port_params.eDomain = OMX_PortDomainVideo;
  422. in_port_params.format.video.pNativeRender = NULL;
  423. in_port_params.format.video.bFlagErrorConcealment = OMX_FALSE;
  424. in_port_params.format.video.eColorFormat = s->color_format;
  425. s->stride = avctx->width;
  426. s->plane_size = avctx->height;
  427. // If specific codecs need to manually override the stride/plane_size,
  428. // that can be done here.
  429. in_port_params.format.video.nStride = s->stride;
  430. in_port_params.format.video.nSliceHeight = s->plane_size;
  431. in_port_params.format.video.nFrameWidth = avctx->width;
  432. in_port_params.format.video.nFrameHeight = avctx->height;
  433. if (avctx->framerate.den > 0 && avctx->framerate.num > 0)
  434. in_port_params.format.video.xFramerate = (1 << 16) * avctx->framerate.num / avctx->framerate.den;
  435. else
  436. in_port_params.format.video.xFramerate = (1 << 16) * avctx->time_base.den / avctx->time_base.num;
  437. err = OMX_SetParameter(s->handle, OMX_IndexParamPortDefinition, &in_port_params);
  438. CHECK(err);
  439. err = OMX_GetParameter(s->handle, OMX_IndexParamPortDefinition, &in_port_params);
  440. CHECK(err);
  441. s->stride = in_port_params.format.video.nStride;
  442. s->plane_size = in_port_params.format.video.nSliceHeight;
  443. s->num_in_buffers = in_port_params.nBufferCountActual;
  444. err = OMX_GetParameter(s->handle, OMX_IndexParamPortDefinition, &out_port_params);
  445. out_port_params.bEnabled = OMX_TRUE;
  446. out_port_params.bPopulated = OMX_FALSE;
  447. out_port_params.eDomain = OMX_PortDomainVideo;
  448. out_port_params.format.video.pNativeRender = NULL;
  449. out_port_params.format.video.nFrameWidth = avctx->width;
  450. out_port_params.format.video.nFrameHeight = avctx->height;
  451. out_port_params.format.video.nStride = 0;
  452. out_port_params.format.video.nSliceHeight = 0;
  453. out_port_params.format.video.nBitrate = avctx->bit_rate;
  454. out_port_params.format.video.xFramerate = in_port_params.format.video.xFramerate;
  455. out_port_params.format.video.bFlagErrorConcealment = OMX_FALSE;
  456. if (avctx->codec->id == AV_CODEC_ID_MPEG4)
  457. out_port_params.format.video.eCompressionFormat = OMX_VIDEO_CodingMPEG4;
  458. else if (avctx->codec->id == AV_CODEC_ID_H264)
  459. out_port_params.format.video.eCompressionFormat = OMX_VIDEO_CodingAVC;
  460. err = OMX_SetParameter(s->handle, OMX_IndexParamPortDefinition, &out_port_params);
  461. CHECK(err);
  462. err = OMX_GetParameter(s->handle, OMX_IndexParamPortDefinition, &out_port_params);
  463. CHECK(err);
  464. s->num_out_buffers = out_port_params.nBufferCountActual;
  465. INIT_STRUCT(vid_param_bitrate);
  466. vid_param_bitrate.nPortIndex = s->out_port;
  467. vid_param_bitrate.eControlRate = OMX_Video_ControlRateVariable;
  468. vid_param_bitrate.nTargetBitrate = avctx->bit_rate;
  469. err = OMX_SetParameter(s->handle, OMX_IndexParamVideoBitrate, &vid_param_bitrate);
  470. if (err != OMX_ErrorNone)
  471. av_log(avctx, AV_LOG_WARNING, "Unable to set video bitrate parameter\n");
  472. if (avctx->codec->id == AV_CODEC_ID_H264) {
  473. OMX_VIDEO_PARAM_AVCTYPE avc = { 0 };
  474. INIT_STRUCT(avc);
  475. avc.nPortIndex = s->out_port;
  476. err = OMX_GetParameter(s->handle, OMX_IndexParamVideoAvc, &avc);
  477. CHECK(err);
  478. avc.nBFrames = 0;
  479. avc.nPFrames = avctx->gop_size - 1;
  480. err = OMX_SetParameter(s->handle, OMX_IndexParamVideoAvc, &avc);
  481. CHECK(err);
  482. }
  483. err = OMX_SendCommand(s->handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
  484. CHECK(err);
  485. s->in_buffer_headers = av_mallocz(sizeof(OMX_BUFFERHEADERTYPE*) * s->num_in_buffers);
  486. s->free_in_buffers = av_mallocz(sizeof(OMX_BUFFERHEADERTYPE*) * s->num_in_buffers);
  487. s->out_buffer_headers = av_mallocz(sizeof(OMX_BUFFERHEADERTYPE*) * s->num_out_buffers);
  488. s->done_out_buffers = av_mallocz(sizeof(OMX_BUFFERHEADERTYPE*) * s->num_out_buffers);
  489. if (!s->in_buffer_headers || !s->free_in_buffers || !s->out_buffer_headers || !s->done_out_buffers)
  490. return AVERROR(ENOMEM);
  491. for (i = 0; i < s->num_in_buffers && err == OMX_ErrorNone; i++) {
  492. if (s->input_zerocopy)
  493. err = OMX_UseBuffer(s->handle, &s->in_buffer_headers[i], s->in_port, s, in_port_params.nBufferSize, NULL);
  494. else
  495. err = OMX_AllocateBuffer(s->handle, &s->in_buffer_headers[i], s->in_port, s, in_port_params.nBufferSize);
  496. if (err == OMX_ErrorNone)
  497. s->in_buffer_headers[i]->pAppPrivate = s->in_buffer_headers[i]->pOutputPortPrivate = NULL;
  498. }
  499. CHECK(err);
  500. s->num_in_buffers = i;
  501. for (i = 0; i < s->num_out_buffers && err == OMX_ErrorNone; i++)
  502. err = OMX_AllocateBuffer(s->handle, &s->out_buffer_headers[i], s->out_port, s, out_port_params.nBufferSize);
  503. CHECK(err);
  504. s->num_out_buffers = i;
  505. if (wait_for_state(s, OMX_StateIdle) < 0) {
  506. av_log(avctx, AV_LOG_ERROR, "Didn't get OMX_StateIdle\n");
  507. return AVERROR_UNKNOWN;
  508. }
  509. err = OMX_SendCommand(s->handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
  510. CHECK(err);
  511. if (wait_for_state(s, OMX_StateExecuting) < 0) {
  512. av_log(avctx, AV_LOG_ERROR, "Didn't get OMX_StateExecuting\n");
  513. return AVERROR_UNKNOWN;
  514. }
  515. for (i = 0; i < s->num_out_buffers && err == OMX_ErrorNone; i++)
  516. err = OMX_FillThisBuffer(s->handle, s->out_buffer_headers[i]);
  517. if (err != OMX_ErrorNone) {
  518. for (; i < s->num_out_buffers; i++)
  519. s->done_out_buffers[s->num_done_out_buffers++] = s->out_buffer_headers[i];
  520. }
  521. for (i = 0; i < s->num_in_buffers; i++)
  522. s->free_in_buffers[s->num_free_in_buffers++] = s->in_buffer_headers[i];
  523. return err != OMX_ErrorNone ? AVERROR_UNKNOWN : 0;
  524. }
  525. static av_cold void cleanup(OMXCodecContext *s)
  526. {
  527. int i, executing;
  528. pthread_mutex_lock(&s->state_mutex);
  529. executing = s->state == OMX_StateExecuting;
  530. pthread_mutex_unlock(&s->state_mutex);
  531. if (executing) {
  532. OMX_SendCommand(s->handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
  533. wait_for_state(s, OMX_StateIdle);
  534. OMX_SendCommand(s->handle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
  535. for (i = 0; i < s->num_in_buffers; i++) {
  536. OMX_BUFFERHEADERTYPE *buffer = get_buffer(&s->input_mutex, &s->input_cond,
  537. &s->num_free_in_buffers, s->free_in_buffers, 1);
  538. if (s->input_zerocopy)
  539. buffer->pBuffer = NULL;
  540. OMX_FreeBuffer(s->handle, s->in_port, buffer);
  541. }
  542. for (i = 0; i < s->num_out_buffers; i++) {
  543. OMX_BUFFERHEADERTYPE *buffer = get_buffer(&s->output_mutex, &s->output_cond,
  544. &s->num_done_out_buffers, s->done_out_buffers, 1);
  545. OMX_FreeBuffer(s->handle, s->out_port, buffer);
  546. }
  547. wait_for_state(s, OMX_StateLoaded);
  548. }
  549. if (s->handle) {
  550. s->omx_context->ptr_FreeHandle(s->handle);
  551. s->handle = NULL;
  552. }
  553. omx_deinit(s->omx_context);
  554. s->omx_context = NULL;
  555. if (s->mutex_cond_inited) {
  556. pthread_cond_destroy(&s->state_cond);
  557. pthread_mutex_destroy(&s->state_mutex);
  558. pthread_cond_destroy(&s->input_cond);
  559. pthread_mutex_destroy(&s->input_mutex);
  560. pthread_cond_destroy(&s->output_cond);
  561. pthread_mutex_destroy(&s->output_mutex);
  562. s->mutex_cond_inited = 0;
  563. }
  564. av_freep(&s->in_buffer_headers);
  565. av_freep(&s->out_buffer_headers);
  566. av_freep(&s->free_in_buffers);
  567. av_freep(&s->done_out_buffers);
  568. av_freep(&s->output_buf);
  569. }
  570. static av_cold int omx_encode_init(AVCodecContext *avctx)
  571. {
  572. OMXCodecContext *s = avctx->priv_data;
  573. int ret = AVERROR_ENCODER_NOT_FOUND;
  574. const char *role;
  575. OMX_BUFFERHEADERTYPE *buffer;
  576. OMX_ERRORTYPE err;
  577. #if CONFIG_OMX_RPI
  578. s->input_zerocopy = 1;
  579. #endif
  580. s->omx_context = omx_init(avctx, s->libname, s->libprefix);
  581. if (!s->omx_context)
  582. return AVERROR_ENCODER_NOT_FOUND;
  583. pthread_mutex_init(&s->state_mutex, NULL);
  584. pthread_cond_init(&s->state_cond, NULL);
  585. pthread_mutex_init(&s->input_mutex, NULL);
  586. pthread_cond_init(&s->input_cond, NULL);
  587. pthread_mutex_init(&s->output_mutex, NULL);
  588. pthread_cond_init(&s->output_cond, NULL);
  589. s->mutex_cond_inited = 1;
  590. s->avctx = avctx;
  591. s->state = OMX_StateLoaded;
  592. s->error = OMX_ErrorNone;
  593. switch (avctx->codec->id) {
  594. case AV_CODEC_ID_MPEG4:
  595. role = "video_encoder.mpeg4";
  596. break;
  597. case AV_CODEC_ID_H264:
  598. role = "video_encoder.avc";
  599. break;
  600. default:
  601. return AVERROR(ENOSYS);
  602. }
  603. if ((ret = find_component(s->omx_context, avctx, role, s->component_name, sizeof(s->component_name))) < 0)
  604. goto fail;
  605. av_log(avctx, AV_LOG_INFO, "Using %s\n", s->component_name);
  606. if ((ret = omx_component_init(avctx, role)) < 0)
  607. goto fail;
  608. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  609. while (1) {
  610. buffer = get_buffer(&s->output_mutex, &s->output_cond,
  611. &s->num_done_out_buffers, s->done_out_buffers, 1);
  612. if (buffer->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
  613. if ((ret = av_reallocp(&avctx->extradata, avctx->extradata_size + buffer->nFilledLen + AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {
  614. avctx->extradata_size = 0;
  615. goto fail;
  616. }
  617. memcpy(avctx->extradata + avctx->extradata_size, buffer->pBuffer + buffer->nOffset, buffer->nFilledLen);
  618. avctx->extradata_size += buffer->nFilledLen;
  619. memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  620. }
  621. err = OMX_FillThisBuffer(s->handle, buffer);
  622. if (err != OMX_ErrorNone) {
  623. append_buffer(&s->output_mutex, &s->output_cond,
  624. &s->num_done_out_buffers, s->done_out_buffers, buffer);
  625. av_log(avctx, AV_LOG_ERROR, "OMX_FillThisBuffer failed: %x\n", err);
  626. ret = AVERROR_UNKNOWN;
  627. goto fail;
  628. }
  629. if (avctx->codec->id == AV_CODEC_ID_H264) {
  630. // For H.264, the extradata can be returned in two separate buffers
  631. // (the videocore encoder on raspberry pi does this);
  632. // therefore check that we have got both SPS and PPS before continuing.
  633. int nals[32] = { 0 };
  634. int i;
  635. for (i = 0; i + 4 < avctx->extradata_size; i++) {
  636. if (!avctx->extradata[i + 0] &&
  637. !avctx->extradata[i + 1] &&
  638. !avctx->extradata[i + 2] &&
  639. avctx->extradata[i + 3] == 1) {
  640. nals[avctx->extradata[i + 4] & 0x1f]++;
  641. }
  642. }
  643. if (nals[H264_NAL_SPS] && nals[H264_NAL_PPS])
  644. break;
  645. } else {
  646. if (avctx->extradata_size > 0)
  647. break;
  648. }
  649. }
  650. }
  651. return 0;
  652. fail:
  653. return ret;
  654. }
  655. static int omx_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  656. const AVFrame *frame, int *got_packet)
  657. {
  658. OMXCodecContext *s = avctx->priv_data;
  659. int ret = 0;
  660. OMX_BUFFERHEADERTYPE* buffer;
  661. OMX_ERRORTYPE err;
  662. if (frame) {
  663. uint8_t *dst[4];
  664. int linesize[4];
  665. int need_copy;
  666. buffer = get_buffer(&s->input_mutex, &s->input_cond,
  667. &s->num_free_in_buffers, s->free_in_buffers, 1);
  668. buffer->nFilledLen = av_image_fill_arrays(dst, linesize, buffer->pBuffer, avctx->pix_fmt, s->stride, s->plane_size, 1);
  669. if (s->input_zerocopy) {
  670. uint8_t *src[4] = { NULL };
  671. int src_linesize[4];
  672. av_image_fill_arrays(src, src_linesize, frame->data[0], avctx->pix_fmt, s->stride, s->plane_size, 1);
  673. if (frame->linesize[0] == src_linesize[0] &&
  674. frame->linesize[1] == src_linesize[1] &&
  675. frame->linesize[2] == src_linesize[2] &&
  676. frame->data[1] == src[1] &&
  677. frame->data[2] == src[2]) {
  678. // If the input frame happens to have all planes stored contiguously,
  679. // with the right strides, just clone the frame and set the OMX
  680. // buffer header to point to it
  681. AVFrame *local = av_frame_clone(frame);
  682. if (!local) {
  683. // Return the buffer to the queue so it's not lost
  684. append_buffer(&s->input_mutex, &s->input_cond, &s->num_free_in_buffers, s->free_in_buffers, buffer);
  685. return AVERROR(ENOMEM);
  686. } else {
  687. buffer->pAppPrivate = local;
  688. buffer->pOutputPortPrivate = NULL;
  689. buffer->pBuffer = local->data[0];
  690. need_copy = 0;
  691. }
  692. } else {
  693. // If not, we need to allocate a new buffer with the right
  694. // size and copy the input frame into it.
  695. uint8_t *buf = av_malloc(av_image_get_buffer_size(avctx->pix_fmt, s->stride, s->plane_size, 1));
  696. if (!buf) {
  697. // Return the buffer to the queue so it's not lost
  698. append_buffer(&s->input_mutex, &s->input_cond, &s->num_free_in_buffers, s->free_in_buffers, buffer);
  699. return AVERROR(ENOMEM);
  700. } else {
  701. buffer->pAppPrivate = buf;
  702. // Mark that pAppPrivate is an av_malloc'ed buffer, not an AVFrame
  703. buffer->pOutputPortPrivate = (void*) 1;
  704. buffer->pBuffer = buf;
  705. need_copy = 1;
  706. buffer->nFilledLen = av_image_fill_arrays(dst, linesize, buffer->pBuffer, avctx->pix_fmt, s->stride, s->plane_size, 1);
  707. }
  708. }
  709. } else {
  710. need_copy = 1;
  711. }
  712. if (need_copy)
  713. av_image_copy(dst, linesize, (const uint8_t**) frame->data, frame->linesize, avctx->pix_fmt, avctx->width, avctx->height);
  714. buffer->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
  715. buffer->nOffset = 0;
  716. // Convert the timestamps to microseconds; some encoders can ignore
  717. // the framerate and do VFR bit allocation based on timestamps.
  718. buffer->nTimeStamp = to_omx_ticks(av_rescale_q(frame->pts, avctx->time_base, AV_TIME_BASE_Q));
  719. err = OMX_EmptyThisBuffer(s->handle, buffer);
  720. if (err != OMX_ErrorNone) {
  721. append_buffer(&s->input_mutex, &s->input_cond, &s->num_free_in_buffers, s->free_in_buffers, buffer);
  722. av_log(avctx, AV_LOG_ERROR, "OMX_EmptyThisBuffer failed: %x\n", err);
  723. return AVERROR_UNKNOWN;
  724. }
  725. } else if (!s->eos_sent) {
  726. buffer = get_buffer(&s->input_mutex, &s->input_cond,
  727. &s->num_free_in_buffers, s->free_in_buffers, 1);
  728. buffer->nFilledLen = 0;
  729. buffer->nFlags = OMX_BUFFERFLAG_EOS;
  730. buffer->pAppPrivate = buffer->pOutputPortPrivate = NULL;
  731. err = OMX_EmptyThisBuffer(s->handle, buffer);
  732. if (err != OMX_ErrorNone) {
  733. append_buffer(&s->input_mutex, &s->input_cond, &s->num_free_in_buffers, s->free_in_buffers, buffer);
  734. av_log(avctx, AV_LOG_ERROR, "OMX_EmptyThisBuffer failed: %x\n", err);
  735. return AVERROR_UNKNOWN;
  736. }
  737. s->eos_sent = 1;
  738. }
  739. while (!*got_packet && ret == 0 && !s->got_eos) {
  740. // If not flushing, just poll the queue if there's finished packets.
  741. // If flushing, do a blocking wait until we either get a completed
  742. // packet, or get EOS.
  743. buffer = get_buffer(&s->output_mutex, &s->output_cond,
  744. &s->num_done_out_buffers, s->done_out_buffers,
  745. !frame);
  746. if (!buffer)
  747. break;
  748. if (buffer->nFlags & OMX_BUFFERFLAG_EOS)
  749. s->got_eos = 1;
  750. if (buffer->nFlags & OMX_BUFFERFLAG_CODECCONFIG && avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  751. if ((ret = av_reallocp(&avctx->extradata, avctx->extradata_size + buffer->nFilledLen + AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {
  752. avctx->extradata_size = 0;
  753. goto end;
  754. }
  755. memcpy(avctx->extradata + avctx->extradata_size, buffer->pBuffer + buffer->nOffset, buffer->nFilledLen);
  756. avctx->extradata_size += buffer->nFilledLen;
  757. memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  758. } else {
  759. if (!(buffer->nFlags & OMX_BUFFERFLAG_ENDOFFRAME) || !pkt->data) {
  760. // If the output packet isn't preallocated, just concatenate everything in our
  761. // own buffer
  762. int newsize = s->output_buf_size + buffer->nFilledLen + AV_INPUT_BUFFER_PADDING_SIZE;
  763. if ((ret = av_reallocp(&s->output_buf, newsize)) < 0) {
  764. s->output_buf_size = 0;
  765. goto end;
  766. }
  767. memcpy(s->output_buf + s->output_buf_size, buffer->pBuffer + buffer->nOffset, buffer->nFilledLen);
  768. s->output_buf_size += buffer->nFilledLen;
  769. if (buffer->nFlags & OMX_BUFFERFLAG_ENDOFFRAME) {
  770. if ((ret = av_packet_from_data(pkt, s->output_buf, s->output_buf_size)) < 0) {
  771. av_freep(&s->output_buf);
  772. s->output_buf_size = 0;
  773. goto end;
  774. }
  775. s->output_buf = NULL;
  776. s->output_buf_size = 0;
  777. }
  778. } else {
  779. // End of frame, and the caller provided a preallocated frame
  780. if ((ret = ff_alloc_packet(pkt, s->output_buf_size + buffer->nFilledLen)) < 0) {
  781. av_log(avctx, AV_LOG_ERROR, "Error getting output packet of size %d.\n",
  782. (int)(s->output_buf_size + buffer->nFilledLen));
  783. goto end;
  784. }
  785. memcpy(pkt->data, s->output_buf, s->output_buf_size);
  786. memcpy(pkt->data + s->output_buf_size, buffer->pBuffer + buffer->nOffset, buffer->nFilledLen);
  787. av_freep(&s->output_buf);
  788. s->output_buf_size = 0;
  789. }
  790. if (buffer->nFlags & OMX_BUFFERFLAG_ENDOFFRAME) {
  791. pkt->pts = av_rescale_q(from_omx_ticks(buffer->nTimeStamp), AV_TIME_BASE_Q, avctx->time_base);
  792. // We don't currently enable B-frames for the encoders, so set
  793. // pkt->dts = pkt->pts. (The calling code behaves worse if the encoder
  794. // doesn't set the dts).
  795. pkt->dts = pkt->pts;
  796. if (buffer->nFlags & OMX_BUFFERFLAG_SYNCFRAME)
  797. pkt->flags |= AV_PKT_FLAG_KEY;
  798. *got_packet = 1;
  799. }
  800. }
  801. end:
  802. err = OMX_FillThisBuffer(s->handle, buffer);
  803. if (err != OMX_ErrorNone) {
  804. append_buffer(&s->output_mutex, &s->output_cond, &s->num_done_out_buffers, s->done_out_buffers, buffer);
  805. av_log(avctx, AV_LOG_ERROR, "OMX_FillThisBuffer failed: %x\n", err);
  806. ret = AVERROR_UNKNOWN;
  807. }
  808. }
  809. return ret;
  810. }
  811. static av_cold int omx_encode_end(AVCodecContext *avctx)
  812. {
  813. OMXCodecContext *s = avctx->priv_data;
  814. cleanup(s);
  815. return 0;
  816. }
  817. #define OFFSET(x) offsetof(OMXCodecContext, x)
  818. #define VDE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  819. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  820. static const AVOption options[] = {
  821. { "omx_libname", "OpenMAX library name", OFFSET(libname), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VDE },
  822. { "omx_libprefix", "OpenMAX library prefix", OFFSET(libprefix), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VDE },
  823. { "zerocopy", "Try to avoid copying input frames if possible", OFFSET(input_zerocopy), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  824. { NULL }
  825. };
  826. static const enum AVPixelFormat omx_encoder_pix_fmts[] = {
  827. AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE
  828. };
  829. static const AVClass omx_mpeg4enc_class = {
  830. .class_name = "mpeg4_omx",
  831. .item_name = av_default_item_name,
  832. .option = options,
  833. .version = LIBAVUTIL_VERSION_INT,
  834. };
  835. AVCodec ff_mpeg4_omx_encoder = {
  836. .name = "mpeg4_omx",
  837. .long_name = NULL_IF_CONFIG_SMALL("OpenMAX IL MPEG-4 video encoder"),
  838. .type = AVMEDIA_TYPE_VIDEO,
  839. .id = AV_CODEC_ID_MPEG4,
  840. .priv_data_size = sizeof(OMXCodecContext),
  841. .init = omx_encode_init,
  842. .encode2 = omx_encode_frame,
  843. .close = omx_encode_end,
  844. .pix_fmts = omx_encoder_pix_fmts,
  845. .capabilities = AV_CODEC_CAP_DELAY,
  846. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,
  847. .priv_class = &omx_mpeg4enc_class,
  848. };
  849. static const AVClass omx_h264enc_class = {
  850. .class_name = "h264_omx",
  851. .item_name = av_default_item_name,
  852. .option = options,
  853. .version = LIBAVUTIL_VERSION_INT,
  854. };
  855. AVCodec ff_h264_omx_encoder = {
  856. .name = "h264_omx",
  857. .long_name = NULL_IF_CONFIG_SMALL("OpenMAX IL H.264 video encoder"),
  858. .type = AVMEDIA_TYPE_VIDEO,
  859. .id = AV_CODEC_ID_H264,
  860. .priv_data_size = sizeof(OMXCodecContext),
  861. .init = omx_encode_init,
  862. .encode2 = omx_encode_frame,
  863. .close = omx_encode_end,
  864. .pix_fmts = omx_encoder_pix_fmts,
  865. .capabilities = AV_CODEC_CAP_DELAY,
  866. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,
  867. .priv_class = &omx_h264enc_class,
  868. };