lin
2025-08-14 dae8bad597b6607a449b32bf76c523423f7720ed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/*
 * drm_display.cpp - drm display
 *
 *  Copyright (c) 2015 Intel Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author: John Ye <john.ye@intel.com>
 */
 
 
#include "drm_display.h"
#include "drm_v4l2_buffer.h"
#include "drm_bo_buffer.h"
#include <drm_fourcc.h>
#include <sys/ioctl.h>
#include <fcntl.h>
 
 
#define DEFAULT_DRM_DEVICE "i915"
#define DEFAULT_DRM_BUSID "PCI:00:02:00"
#define DEFAULT_DRM_BATCH_SIZE 0x80000
 
namespace XCam {
 
SmartPtr<DrmDisplay> DrmDisplay::_instance(NULL);
Mutex DrmDisplay::_mutex;
 
static std::atomic<uint32_t> global_signal_index(0);
 
bool DrmDisplay::_preview_flag = false;
 
bool
DrmDisplay::set_preview (bool flag) {
    if (_instance.ptr () && flag != _preview_flag)
        return false;
    _preview_flag = flag;
    return true;
};
 
SmartPtr<DrmDisplay>
DrmDisplay::instance ()
{
    SmartLock lock(_mutex);
    if (_instance.ptr())
        return _instance;
    _instance = new DrmDisplay ();
    return _instance;
}
 
DrmDisplay::DrmDisplay (const char *module)
    : _module(NULL)
    , _fd (-1)
    , _buf_manager (NULL)
    , _display_mode (DRM_DISPLAY_MODE_NONE)
    , _crtc_index (-1)
    , _crtc_id (0)
    , _con_id (0)
    , _encoder_id (0)
    , _plane_id (0)
    , _connector (NULL)
    , _is_render_inited (false)
    , _format (0)
    , _width (0)
    , _height (0)
{
    xcam_mem_clear(_compose);
 
    if (module)
        _module = strndup (module, XCAM_MAX_STR_SIZE);
    else
        _module = strndup (DEFAULT_DRM_DEVICE, XCAM_MAX_STR_SIZE);
 
    if (!_preview_flag) {
        _fd = open_drivers ("/dev/dri/renderD", 128);
    }
 
    if (_fd < 0)
        _fd = open_drivers ("/dev/dri/card", 0);
 
    if (_fd < 0) {
        _fd = drmOpen (_module, DEFAULT_DRM_BUSID);
        if (_fd >= 0 && !is_authenticated (_fd, DEFAULT_DRM_BUSID)) {
            drmClose (_fd);
            _fd = -1;
        }
    }
 
    if (_fd < 0) {
        XCAM_LOG_WARNING ("please try root privilege if without X server");
        XCAM_LOG_ERROR ("failed to open drm device %s", XCAM_STR (_module));
    }
 
    _buf_manager = drm_intel_bufmgr_gem_init (_fd, DEFAULT_DRM_BATCH_SIZE);
    drm_intel_bufmgr_gem_enable_reuse (_buf_manager);
}
 
DrmDisplay::~DrmDisplay()
{
    _display_buf.release ();
 
    if (_buf_manager)
        drm_intel_bufmgr_destroy (_buf_manager);
    if (_fd >= 0)
        drmClose (_fd);
    if (_module)
        xcam_free (_module);
};
 
int
DrmDisplay::open_drivers (const char *base_path, int base_id)
{
    int fd = -1;
    char dev_path [32];
    XCAM_ASSERT (base_path);
 
    for (int i = 0; i < 16; i++) {
        sprintf (dev_path, "%s%d", base_path, base_id + i);
        if (access (dev_path, F_OK) != 0)
            continue;
 
        fd = open_driver (dev_path);
        if (fd >= 0)
            break;
    }
 
    return fd;
}
 
int
DrmDisplay::open_driver (const char *dev_path)
{
    XCAM_ASSERT (dev_path);
 
    int fd = open (dev_path, O_RDWR);
    if (fd < 0) {
        XCAM_LOG_ERROR ("failed to open %s", dev_path);
        return -1;
    }
 
    if (!strncmp (dev_path, "/dev/dri/card", 13)) {
        if (!is_authenticated (fd, dev_path)) {
            close (fd);
            return -1;
        }
    }
 
    return fd;
}
 
bool
DrmDisplay::is_authenticated (int fd, const char *msg)
{
    drm_client_t client;
    memset (&client, 0, sizeof (drm_client_t));
    if (ioctl (fd, DRM_IOCTL_GET_CLIENT, &client) == -1) {
        XCAM_LOG_ERROR ("failed to get drm client");
        return false;
    }
 
    if (!client.auth) {
        XCAM_LOG_ERROR ("%s is not authenticated", msg);
        return false;
    }
 
    return true;
}
 
uint32_t
DrmDisplay::to_drm_fourcc (uint32_t fourcc_of_v4l2)
{
    switch (fourcc_of_v4l2) {
    case V4L2_PIX_FMT_RGB565:
        return DRM_FORMAT_RGB565;
    default:
        break;
    }
    return fourcc_of_v4l2;
}
 
XCamReturn
DrmDisplay::get_crtc(drmModeRes *res)
{
    _crtc_index = -1;
 
    drmModeEncoderPtr encoder = drmModeGetEncoder(_fd, _encoder_id);
    XCAM_FAIL_RETURN(ERROR, encoder, XCAM_RETURN_ERROR_PARAM,
                     "drmModeGetEncoder failed: %s", strerror(errno));
 
    _crtc_id = encoder->crtc_id;
    drmModeFreeEncoder(encoder);
 
    for (int i = 0; i < res->count_crtcs; i++) {
        if (_crtc_id == res->crtcs[i]) {
            _crtc_index = i;
            break;
        }
    }
    XCAM_FAIL_RETURN(ERROR, _crtc_index != -1, XCAM_RETURN_ERROR_PARAM,
                     "CRTC %d not found", _crtc_id);
 
    return XCAM_RETURN_NO_ERROR;
}
 
XCamReturn
DrmDisplay::get_connector(drmModeRes *res)
{
    XCAM_FAIL_RETURN(ERROR, res->count_connectors > 0, XCAM_RETURN_ERROR_PARAM,
                     "No connector found");
    for(int i = 0; i < res->count_connectors; ++i) {
        _connector = drmModeGetConnector(_fd, res->connectors[i]);
        if(_connector && _connector->connection == DRM_MODE_CONNECTED) {
            _con_id = res->connectors[i];
            _encoder_id = res->encoders[i];
            _mode = *_connector->modes;
        }
        drmModeFreeConnector(_connector);
    }
    XCAM_FAIL_RETURN(ERROR, _connector, XCAM_RETURN_ERROR_PARAM,
                     "drmModeGetConnector failed: %s", strerror(errno));
 
    return XCAM_RETURN_NO_ERROR;
}
 
 
XCamReturn
DrmDisplay::get_plane()
{
    drmModePlaneResPtr planes = drmModeGetPlaneResources(_fd);
    XCAM_FAIL_RETURN(ERROR, planes, XCAM_RETURN_ERROR_PARAM,
                     "failed to query planes: %s", strerror(errno));
 
    drmModePlanePtr plane = NULL;
    for (uint32_t i = 0; i < planes->count_planes; i++) {
        if (plane) {
            drmModeFreePlane(plane);
            plane = NULL;
        }
        plane = drmModeGetPlane(_fd, planes->planes[i]);
        XCAM_FAIL_RETURN(ERROR, plane, XCAM_RETURN_ERROR_PARAM,
                         "failed to query plane %d: %s", i, strerror(errno));
 
        if (plane->crtc_id || !(plane->possible_crtcs & (1 << _crtc_index))) {
            continue;
        }
 
        for (uint32_t j = 0; j < plane->count_formats; j++) {
            // found a plane matching the requested format
            if (plane->formats[j] == _format) {
                _plane_id = plane->plane_id;
                drmModeFreePlane(plane);
                drmModeFreePlaneResources(planes);
                return XCAM_RETURN_NO_ERROR;
            }
        }
    }
 
    if (plane)
        drmModeFreePlane(plane);
 
    drmModeFreePlaneResources(planes);
 
    return XCAM_RETURN_ERROR_PARAM;
}
 
XCamReturn
DrmDisplay::render_init (
    uint32_t con_id,
    uint32_t crtc_id,
    uint32_t width,
    uint32_t height,
    uint32_t format,
    const struct v4l2_rect* compose)
{
    XCamReturn ret = XCAM_RETURN_NO_ERROR;
 
    if (is_render_inited ())
        return ret;
 
    _con_id = con_id;
    _crtc_id = crtc_id;
    _width = width;
    _height = height;
    _format = to_drm_fourcc (format);
    _compose = *compose;
    _crtc_index = -1;
    _plane_id = 0;
    _connector = NULL;
 
    drmModeRes *resource = drmModeGetResources(_fd);
    XCAM_FAIL_RETURN(ERROR, resource, XCAM_RETURN_ERROR_PARAM,
                     "failed to query Drm Mode resources: %s", strerror(errno));
 
    ret = get_connector(resource);
    XCAM_FAIL_RETURN(ERROR, ret == XCAM_RETURN_NO_ERROR,
                     XCAM_RETURN_ERROR_PARAM,
                     "failed to get connector %s", strerror(errno));
 
    ret = get_crtc(resource);
    XCAM_FAIL_RETURN(ERROR, ret == XCAM_RETURN_NO_ERROR,
                     XCAM_RETURN_ERROR_PARAM,
                     "failed to get CRTC %s", strerror(errno));
 
    ret = get_plane();
    XCAM_FAIL_RETURN(ERROR, ret == XCAM_RETURN_NO_ERROR,
                     XCAM_RETURN_ERROR_PARAM,
                     "failed to get plane with required format %s", strerror(errno));
 
    drmModeFreeResources(resource);
    if (_display_mode ==  DRM_DISPLAY_MODE_OVERLAY)
        _is_render_inited = true;
    return XCAM_RETURN_NO_ERROR;
}
 
 
SmartPtr<V4l2Buffer>
DrmDisplay::create_drm_buf (
    const struct v4l2_format &format,
    const uint32_t index,
    const enum v4l2_buf_type buf_type)
{
    struct drm_mode_create_dumb gem;
    struct drm_prime_handle prime;
    struct v4l2_buffer v4l2_buf;
    int ret = 0;
 
    xcam_mem_clear (gem);
    xcam_mem_clear (prime);
    xcam_mem_clear (v4l2_buf);
 
    gem.width = format.fmt.pix.bytesperline;
    gem.height = format.fmt.pix.height;
    gem.bpp = 8;
    ret = xcam_device_ioctl (_fd, DRM_IOCTL_MODE_CREATE_DUMB, &gem);
    XCAM_ASSERT (ret >= 0);
 
    prime.handle = gem.handle;
    ret = xcam_device_ioctl (_fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &prime);
    if (ret < 0) {
        XCAM_LOG_WARNING ("create drm failed on DRM_IOCTL_PRIME_HANDLE_TO_FD");
        return NULL;
    }
 
    v4l2_buf.index = index;
    v4l2_buf.type = buf_type;
    v4l2_buf.memory = V4L2_MEMORY_DMABUF;
    v4l2_buf.m.fd = prime.fd;
    v4l2_buf.length = XCAM_MAX (format.fmt.pix.sizeimage, gem.size); // todo check gem.size and format.fmt.pix.length
    XCAM_LOG_DEBUG ("create drm buffer size:%lld", gem.size);
    return new DrmV4l2Buffer (gem.handle, v4l2_buf, format, _instance);
}
 
XCamReturn
DrmDisplay::render_setup_frame_buffer (SmartPtr<VideoBuffer> &buf)
{
    XCamReturn ret = XCAM_RETURN_NO_ERROR;
    VideoBufferInfo video_info = buf->get_video_info ();
    uint32_t fourcc = video_info.format;
    uint32_t fb_handle = 0;
    uint32_t bo_handle = 0;
    uint32_t bo_handles[4] = { 0 };
    FB fb;
    SmartPtr<V4l2BufferProxy> v4l2_proxy;
    SmartPtr<DrmBoBuffer> bo_buf;
 
    v4l2_proxy = buf.dynamic_cast_ptr<V4l2BufferProxy> ();
    bo_buf = buf.dynamic_cast_ptr<DrmBoBuffer> ();
    if (v4l2_proxy.ptr ()) {
        struct drm_prime_handle prime;
        memset(&prime, 0, sizeof (prime));
        prime.fd = v4l2_proxy->get_v4l2_dma_fd();
 
        ret = (XCamReturn) xcam_device_ioctl(_fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &prime);
        if (ret) {
            XCAM_LOG_WARNING("FD_TO_PRIME_HANDLE failed: %s", strerror(errno));
            return XCAM_RETURN_ERROR_IOCTL;
        }
        bo_handle = prime.handle;
    } else if (bo_buf.ptr ()) {
        const drm_intel_bo* bo = bo_buf->get_bo ();
        XCAM_ASSERT (bo);
        bo_handle = bo->handle;
    } else {
        XCAM_ASSERT (false);
        XCAM_LOG_WARNING("drm setup framebuffer doesn't support this buffer");
        return XCAM_RETURN_ERROR_PARAM;
    }
 
    for (uint32_t i = 0; i < 4; ++i) {
        bo_handles [i] = bo_handle;
    }
 
    ret = (XCamReturn) drmModeAddFB2(_fd, video_info.width, video_info.height, fourcc, bo_handles,
                                     video_info.strides, video_info.offsets, &fb_handle, 0);
 
    fb.fb_handle = fb_handle;
    fb.index = global_signal_index++;
    _buf_fb_handles[buf.ptr ()] = fb;
 
    XCAM_FAIL_RETURN(ERROR, ret == XCAM_RETURN_NO_ERROR, XCAM_RETURN_ERROR_PARAM,
                     "drmModeAddFB2 failed: %s", strerror(errno));
 
    return ret;
}
 
XCamReturn
DrmDisplay::set_crtc (const FB &fb)
{
    XCamReturn ret = XCAM_RETURN_NO_ERROR;
    uint32_t fb_handle = fb.fb_handle;
    //uint32_t index = fb.index;
 
    if( !_is_render_inited) {
        ret = (XCamReturn) drmModeSetCrtc(_fd,  _crtc_id, fb_handle, 0,
                                          0, &_con_id, 1, &_mode);
        XCAM_FAIL_RETURN(ERROR, ret == XCAM_RETURN_NO_ERROR, XCAM_RETURN_ERROR_IOCTL,
                         "failed to set crct via drm: %s", strerror(errno));
        _is_render_inited = true;
    }
    return ret;
}
 
XCamReturn
DrmDisplay::set_plane (const FB &fb)
{
    XCamReturn ret = XCAM_RETURN_NO_ERROR;
    uint32_t fb_handle = fb.fb_handle;
    //uint32_t index = fb.index;
 
    ret = (XCamReturn) drmModeSetPlane(_fd, _plane_id, _crtc_id,
                                       fb_handle, 0,
                                       _compose.left, _compose.top,
                                       _compose.width, _compose.height,
                                       0, 0, _width << 16, _height << 16);
    XCAM_FAIL_RETURN(ERROR, ret == XCAM_RETURN_NO_ERROR, XCAM_RETURN_ERROR_IOCTL,
                     "failed to set plane via drm: %s", strerror(errno));
#if 0
    drmVBlank vblank;
    vblank.request.type = (drmVBlankSeqType) (DRM_VBLANK_EVENT | DRM_VBLANK_RELATIVE);
    vblank.request.sequence = 1;
    vblank.request.signal = (unsigned long) index;
    ret = (XCamReturn) drmWaitVBlank(_fd, &vblank);
    XCAM_FAIL_RETURN(ERROR, ret == XCAM_RETURN_NO_ERROR, XCAM_RETURN_ERROR_IOCTL,
                     "failed to wait vblank: %s", strerror(errno));
#endif
    return XCAM_RETURN_NO_ERROR;
}
 
XCamReturn
DrmDisplay::page_flip (const FB &fb)
{
    XCamReturn ret;
    uint32_t fb_handle = fb.fb_handle;
    uint32_t index = fb.index;
 
    ret = (XCamReturn) drmModePageFlip(_fd, _crtc_id, fb_handle,
                                       DRM_MODE_PAGE_FLIP_EVENT,
                                       (void*)(unsigned long) index);
    XCAM_FAIL_RETURN(ERROR, ret == XCAM_RETURN_NO_ERROR, XCAM_RETURN_ERROR_IOCTL,
                     "failed on page flip: %s", strerror(errno));
 
    drmEventContext evctx;
    struct timeval timeout = { .tv_sec = 3, .tv_usec = 0 };
    fd_set fds;
    memset(&evctx, 0, sizeof evctx);
    evctx.version = DRM_EVENT_CONTEXT_VERSION;
    evctx.vblank_handler = NULL;
    //evctx.page_flip_handler = page_flip_handler;
    FD_ZERO(&fds);
    FD_SET(_fd, &fds);
    select(_fd + 1, &fds, NULL, NULL, &timeout);
    drmHandleEvent(_fd, &evctx);
 
    return XCAM_RETURN_NO_ERROR;
}
 
XCamReturn
DrmDisplay::render_buffer(SmartPtr<VideoBuffer> &buf)
{
    XCamReturn ret = XCAM_RETURN_NO_ERROR;
    FBMap::iterator iter = _buf_fb_handles.find (buf.ptr ());
    XCAM_FAIL_RETURN(
        ERROR,
        iter != _buf_fb_handles.end (),
        XCAM_RETURN_ERROR_PARAM,
        "buffer not register on framebuf");
    if(_display_mode == DRM_DISPLAY_MODE_OVERLAY)
        ret = _plane_id ? set_plane(iter->second) : page_flip(iter->second);
    else if(_display_mode == DRM_DISPLAY_MODE_PRIMARY) {
        ret = set_crtc (iter->second);
        ret = page_flip (iter->second);
    }
    _display_buf = buf;
 
    return ret;
}
 
SmartPtr<DrmBoBuffer>
DrmDisplay::convert_to_drm_bo_buf (SmartPtr<DrmDisplay> &self, SmartPtr<VideoBuffer> &buf_in)
{
    drm_intel_bo *bo = NULL;
    int dma_fd = 0;
    SmartPtr<DrmBoBuffer> new_bo_buf;
    SmartPtr<DrmBoData> bo_data;
 
    XCAM_ASSERT (self.ptr () == this);
    XCAM_ASSERT (buf_in.ptr ());
 
    new_bo_buf = buf_in.dynamic_cast_ptr<DrmBoBuffer> ();
    if (new_bo_buf.ptr ())
        return new_bo_buf;
 
    const VideoBufferInfo video_info = buf_in->get_video_info ();
    dma_fd = buf_in->get_fd ();
    if (dma_fd < 0) {
        XCAM_LOG_DEBUG ("DrmDisplay only support dma buffer conversion to drm bo by now");
        return NULL;
    }
 
    bo = drm_intel_bo_gem_create_from_prime (_buf_manager, dma_fd, video_info.size);
    if (bo == NULL) {
        XCAM_LOG_WARNING ("convert dma fd to drm bo failed");
        return NULL;
    }
    bo_data = new DrmBoData (self, bo);
    bo_data->set_prime_fd (dma_fd, false);
    new_bo_buf = new DrmBoBuffer (video_info, bo_data);
    new_bo_buf->set_parent (buf_in);
    new_bo_buf->set_timestamp (buf_in->get_timestamp ());
    return new_bo_buf;
}
 
SmartPtr<DrmBoData>
DrmDisplay::create_drm_bo (SmartPtr<DrmDisplay> &self, const VideoBufferInfo &info)
{
    SmartPtr<DrmBoData> new_bo;
 
    XCAM_ASSERT (_buf_manager);
    XCAM_ASSERT (self.ptr() == this);
    drm_intel_bo *bo = drm_intel_bo_alloc (
                           _buf_manager, "xcam drm bo buf", info.size, 0x1000);
 
    new_bo = new DrmBoData (self, bo);
    return new_bo;
}
 
drm_intel_bo *
DrmDisplay::create_drm_bo_from_fd (int32_t fd, uint32_t size)
{
    drm_intel_bo *bo = NULL;
    XCAM_ASSERT (_buf_manager);
    bo = drm_intel_bo_gem_create_from_prime (_buf_manager, fd, size);
 
    XCAM_ASSERT (bo);
    return bo;
}
 
 
};