Merge "Improve MV prediction in vp8_pick_inter_mode() for speed>3"
[profile/ivi/libvpx.git] / vp8 / encoder / ethreading.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include "onyx_int.h"
12 #include "threading.h"
13 #include "common.h"
14 #include "extend.h"
15
16 extern int vp8cx_encode_inter_macroblock(VP8_COMP *cpi, MACROBLOCK *x,
17                                          TOKENEXTRA **t, int recon_yoffset,
18                                          int recon_uvoffset);
19 extern int vp8cx_encode_intra_macro_block(VP8_COMP *cpi, MACROBLOCK *x,
20                                           TOKENEXTRA **t);
21 extern void vp8cx_mb_init_quantizer(VP8_COMP *cpi, MACROBLOCK *x);
22 extern void vp8_build_block_offsets(MACROBLOCK *x);
23 extern void vp8_setup_block_ptrs(MACROBLOCK *x);
24
25 static
26 THREAD_FUNCTION thread_encoding_proc(void *p_data)
27 {
28 #if CONFIG_MULTITHREAD
29     int ithread = ((ENCODETHREAD_DATA *)p_data)->ithread;
30     VP8_COMP *cpi = (VP8_COMP *)(((ENCODETHREAD_DATA *)p_data)->ptr1);
31     MB_ROW_COMP *mbri = (MB_ROW_COMP *)(((ENCODETHREAD_DATA *)p_data)->ptr2);
32     ENTROPY_CONTEXT_PLANES mb_row_left_context;
33
34     const int nsync = cpi->mt_sync_range;
35     //printf("Started thread %d\n", ithread);
36
37     while (1)
38     {
39         if (cpi->b_multi_threaded == 0)
40             break;
41
42         //if(WaitForSingleObject(cpi->h_event_mbrencoding[ithread], INFINITE) == WAIT_OBJECT_0)
43         if (sem_wait(&cpi->h_event_start_encoding[ithread]) == 0)
44         {
45             VP8_COMMON *cm = &cpi->common;
46             int mb_row;
47             MACROBLOCK *x = &mbri->mb;
48             MACROBLOCKD *xd = &x->e_mbd;
49             TOKENEXTRA *tp ;
50
51             int *segment_counts = mbri->segment_counts;
52             int *totalrate = &mbri->totalrate;
53
54             if (cpi->b_multi_threaded == FALSE) // we're shutting down
55                 break;
56
57             for (mb_row = ithread + 1; mb_row < cm->mb_rows; mb_row += (cpi->encoding_thread_count + 1))
58             {
59
60                 int i;
61                 int recon_yoffset, recon_uvoffset;
62                 int mb_col;
63                 int ref_fb_idx = cm->lst_fb_idx;
64                 int dst_fb_idx = cm->new_fb_idx;
65                 int recon_y_stride = cm->yv12_fb[ref_fb_idx].y_stride;
66                 int recon_uv_stride = cm->yv12_fb[ref_fb_idx].uv_stride;
67                 volatile int *last_row_current_mb_col;
68                 INT64 activity_sum = 0;
69
70                 tp = cpi->tok + (mb_row * (cm->mb_cols * 16 * 24));
71
72                 last_row_current_mb_col = &cpi->mt_current_mb_col[mb_row - 1];
73
74                 // reset above block coeffs
75                 xd->above_context = cm->above_context;
76                 xd->left_context = &mb_row_left_context;
77
78                 vp8_zero(mb_row_left_context);
79
80                 xd->up_available = (mb_row != 0);
81                 recon_yoffset = (mb_row * recon_y_stride * 16);
82                 recon_uvoffset = (mb_row * recon_uv_stride * 8);
83
84                 cpi->tplist[mb_row].start = tp;
85
86                 //printf("Thread mb_row = %d\n", mb_row);
87
88                 // for each macroblock col in image
89                 for (mb_col = 0; mb_col < cm->mb_cols; mb_col++)
90                 {
91                     int seg_map_index = (mb_row * cm->mb_cols);
92
93                     if ((mb_col & (nsync - 1)) == 0)
94                     {
95                         while (mb_col > (*last_row_current_mb_col - nsync) && *last_row_current_mb_col != cm->mb_cols - 1)
96                         {
97                             x86_pause_hint();
98                             thread_sleep(0);
99                         }
100                     }
101
102                     // Distance of Mb to the various image edges.
103                     // These specified to 8th pel as they are always compared to values that are in 1/8th pel units
104                     xd->mb_to_left_edge = -((mb_col * 16) << 3);
105                     xd->mb_to_right_edge = ((cm->mb_cols - 1 - mb_col) * 16) << 3;
106                     xd->mb_to_top_edge = -((mb_row * 16) << 3);
107                     xd->mb_to_bottom_edge = ((cm->mb_rows - 1 - mb_row) * 16) << 3;
108
109                     // Set up limit values for motion vectors used to prevent them extending outside the UMV borders
110                     x->mv_col_min = -((mb_col * 16) + (VP8BORDERINPIXELS - 16));
111                     x->mv_col_max = ((cm->mb_cols - 1 - mb_col) * 16) + (VP8BORDERINPIXELS - 16);
112                     x->mv_row_min = -((mb_row * 16) + (VP8BORDERINPIXELS - 16));
113                     x->mv_row_max = ((cm->mb_rows - 1 - mb_row) * 16) + (VP8BORDERINPIXELS - 16);
114
115                     xd->dst.y_buffer = cm->yv12_fb[dst_fb_idx].y_buffer + recon_yoffset;
116                     xd->dst.u_buffer = cm->yv12_fb[dst_fb_idx].u_buffer + recon_uvoffset;
117                     xd->dst.v_buffer = cm->yv12_fb[dst_fb_idx].v_buffer + recon_uvoffset;
118                     xd->left_available = (mb_col != 0);
119
120                     x->rddiv = cpi->RDDIV;
121                     x->rdmult = cpi->RDMULT;
122
123                     if (cpi->oxcf.tuning == VP8_TUNE_SSIM)
124                         activity_sum += vp8_activity_masking(cpi, x);
125
126                     // Is segmentation enabled
127                     // MB level adjutment to quantizer
128                     if (xd->segmentation_enabled)
129                     {
130                         // Code to set segment id in xd->mbmi.segment_id for current MB (with range checking)
131                         if (cpi->segmentation_map[seg_map_index + mb_col] <= 3)
132                             xd->mode_info_context->mbmi.segment_id = cpi->segmentation_map[seg_map_index + mb_col];
133                         else
134                             xd->mode_info_context->mbmi.segment_id = 0;
135
136                         vp8cx_mb_init_quantizer(cpi, x);
137                     }
138                     else
139                         xd->mode_info_context->mbmi.segment_id = 0; // Set to Segment 0 by default
140
141                     x->active_ptr = cpi->active_map + seg_map_index + mb_col;
142
143                     if (cm->frame_type == KEY_FRAME)
144                     {
145                         *totalrate += vp8cx_encode_intra_macro_block(cpi, x, &tp);
146 #ifdef MODE_STATS
147                         y_modes[xd->mbmi.mode] ++;
148 #endif
149                     }
150                     else
151                     {
152                         *totalrate += vp8cx_encode_inter_macroblock(cpi, x, &tp, recon_yoffset, recon_uvoffset);
153
154 #ifdef MODE_STATS
155                         inter_y_modes[xd->mbmi.mode] ++;
156
157                         if (xd->mbmi.mode == SPLITMV)
158                         {
159                             int b;
160
161                             for (b = 0; b < xd->mbmi.partition_count; b++)
162                             {
163                                 inter_b_modes[x->partition->bmi[b].mode] ++;
164                             }
165                         }
166
167 #endif
168
169                         // Count of last ref frame 0,0 useage
170                         if ((xd->mode_info_context->mbmi.mode == ZEROMV) && (xd->mode_info_context->mbmi.ref_frame == LAST_FRAME))
171                             cpi->inter_zz_count++;
172
173                         // Special case code for cyclic refresh
174                         // If cyclic update enabled then copy xd->mbmi.segment_id; (which may have been updated based on mode
175                         // during vp8cx_encode_inter_macroblock()) back into the global sgmentation map
176                         if (cpi->cyclic_refresh_mode_enabled && xd->segmentation_enabled)
177                         {
178                             const MB_MODE_INFO * mbmi = &xd->mode_info_context->mbmi;
179                             cpi->segmentation_map[seg_map_index + mb_col] = mbmi->segment_id;
180
181                             // If the block has been refreshed mark it as clean (the magnitude of the -ve influences how long it will be before we consider another refresh):
182                             // Else if it was coded (last frame 0,0) and has not already been refreshed then mark it as a candidate for cleanup next time (marked 0)
183                             // else mark it as dirty (1).
184                             if (mbmi->segment_id)
185                                 cpi->cyclic_refresh_map[seg_map_index + mb_col] = -1;
186                             else if ((mbmi->mode == ZEROMV) && (mbmi->ref_frame == LAST_FRAME))
187                             {
188                                 if (cpi->cyclic_refresh_map[seg_map_index + mb_col] == 1)
189                                     cpi->cyclic_refresh_map[seg_map_index + mb_col] = 0;
190                             }
191                             else
192                                 cpi->cyclic_refresh_map[seg_map_index + mb_col] = 1;
193
194                         }
195                     }
196                     cpi->tplist[mb_row].stop = tp;
197
198                     x->gf_active_ptr++; // Increment pointer into gf useage flags structure for next mb
199
200                     for (i = 0; i < 16; i++)
201                         vpx_memcpy(&xd->mode_info_context->bmi[i], &xd->block[i].bmi, sizeof(xd->block[i].bmi));
202
203                     // adjust to the next column of macroblocks
204                     x->src.y_buffer += 16;
205                     x->src.u_buffer += 8;
206                     x->src.v_buffer += 8;
207
208                     recon_yoffset += 16;
209                     recon_uvoffset += 8;
210
211                     // Keep track of segment useage
212                     segment_counts[xd->mode_info_context->mbmi.segment_id]++;
213
214                     // skip to next mb
215                     xd->mode_info_context++;
216                     x->partition_info++;
217                     xd->above_context++;
218
219                     cpi->mt_current_mb_col[mb_row] = mb_col;
220                 }
221
222                 //extend the recon for intra prediction
223                 vp8_extend_mb_row(
224                     &cm->yv12_fb[dst_fb_idx],
225                     xd->dst.y_buffer + 16,
226                     xd->dst.u_buffer + 8,
227                     xd->dst.v_buffer + 8);
228
229                 // this is to account for the border
230                 xd->mode_info_context++;
231                 x->partition_info++;
232                 x->activity_sum += activity_sum;
233
234                 x->src.y_buffer += 16 * x->src.y_stride * (cpi->encoding_thread_count + 1) - 16 * cm->mb_cols;
235                 x->src.u_buffer += 8 * x->src.uv_stride * (cpi->encoding_thread_count + 1) - 8 * cm->mb_cols;
236                 x->src.v_buffer += 8 * x->src.uv_stride * (cpi->encoding_thread_count + 1) - 8 * cm->mb_cols;
237
238                 xd->mode_info_context += xd->mode_info_stride * cpi->encoding_thread_count;
239                 x->partition_info += xd->mode_info_stride * cpi->encoding_thread_count;
240
241                 if (mb_row == cm->mb_rows - 1)
242                 {
243                     //SetEvent(cpi->h_event_main);
244                     sem_post(&cpi->h_event_end_encoding); /* signal frame encoding end */
245                 }
246             }
247         }
248     }
249
250 #else
251     (void) p_data;
252 #endif
253
254     //printf("exit thread %d\n", ithread);
255     return 0;
256 }
257
258 static void setup_mbby_copy(MACROBLOCK *mbdst, MACROBLOCK *mbsrc)
259 {
260
261     MACROBLOCK *x = mbsrc;
262     MACROBLOCK *z = mbdst;
263     int i;
264
265     z->ss               = x->ss;
266     z->ss_count          = x->ss_count;
267     z->searches_per_step  = x->searches_per_step;
268     z->errorperbit      = x->errorperbit;
269
270     z->sadperbit16      = x->sadperbit16;
271     z->sadperbit4       = x->sadperbit4;
272     z->errthresh        = x->errthresh;
273
274     /*
275     z->mv_col_min    = x->mv_col_min;
276     z->mv_col_max    = x->mv_col_max;
277     z->mv_row_min    = x->mv_row_min;
278     z->mv_row_max    = x->mv_row_max;
279     z->vector_range = x->vector_range ;
280     */
281
282     z->vp8_short_fdct4x4     = x->vp8_short_fdct4x4;
283     z->vp8_short_fdct8x4     = x->vp8_short_fdct8x4;
284     z->short_walsh4x4    = x->short_walsh4x4;
285     z->quantize_b        = x->quantize_b;
286     z->optimize          = x->optimize;
287
288     /*
289     z->mvc              = x->mvc;
290     z->src.y_buffer      = x->src.y_buffer;
291     z->src.u_buffer      = x->src.u_buffer;
292     z->src.v_buffer      = x->src.v_buffer;
293     */
294
295
296     vpx_memcpy(z->mvcosts,          x->mvcosts,         sizeof(x->mvcosts));
297     z->mvcost[0] = &z->mvcosts[0][mv_max+1];
298     z->mvcost[1] = &z->mvcosts[1][mv_max+1];
299     z->mvsadcost[0] = &z->mvsadcosts[0][mv_max+1];
300     z->mvsadcost[1] = &z->mvsadcosts[1][mv_max+1];
301
302
303     vpx_memcpy(z->token_costs,       x->token_costs,      sizeof(x->token_costs));
304     vpx_memcpy(z->inter_bmode_costs,  x->inter_bmode_costs, sizeof(x->inter_bmode_costs));
305     //memcpy(z->mvcosts,            x->mvcosts,         sizeof(x->mvcosts));
306     //memcpy(z->mvcost,         x->mvcost,          sizeof(x->mvcost));
307     vpx_memcpy(z->mbmode_cost,       x->mbmode_cost,      sizeof(x->mbmode_cost));
308     vpx_memcpy(z->intra_uv_mode_cost,  x->intra_uv_mode_cost, sizeof(x->intra_uv_mode_cost));
309     vpx_memcpy(z->bmode_costs,       x->bmode_costs,      sizeof(x->bmode_costs));
310
311     for (i = 0; i < 25; i++)
312     {
313         z->block[i].quant           = x->block[i].quant;
314         z->block[i].quant_fast      = x->block[i].quant_fast;
315         z->block[i].quant_shift     = x->block[i].quant_shift;
316         z->block[i].zbin            = x->block[i].zbin;
317         z->block[i].zrun_zbin_boost   = x->block[i].zrun_zbin_boost;
318         z->block[i].round           = x->block[i].round;
319         /*
320         z->block[i].src             = x->block[i].src;
321         */
322         z->block[i].src_stride       = x->block[i].src_stride;
323         z->block[i].force_empty      = x->block[i].force_empty;
324
325     }
326
327     {
328         MACROBLOCKD *xd = &x->e_mbd;
329         MACROBLOCKD *zd = &z->e_mbd;
330
331         /*
332         zd->mode_info_context = xd->mode_info_context;
333         zd->mode_info        = xd->mode_info;
334
335         zd->mode_info_stride  = xd->mode_info_stride;
336         zd->frame_type       = xd->frame_type;
337         zd->up_available     = xd->up_available   ;
338         zd->left_available   = xd->left_available;
339         zd->left_context     = xd->left_context;
340         zd->last_frame_dc     = xd->last_frame_dc;
341         zd->last_frame_dccons = xd->last_frame_dccons;
342         zd->gold_frame_dc     = xd->gold_frame_dc;
343         zd->gold_frame_dccons = xd->gold_frame_dccons;
344         zd->mb_to_left_edge    = xd->mb_to_left_edge;
345         zd->mb_to_right_edge   = xd->mb_to_right_edge;
346         zd->mb_to_top_edge     = xd->mb_to_top_edge   ;
347         zd->mb_to_bottom_edge  = xd->mb_to_bottom_edge;
348         zd->gf_active_ptr     = xd->gf_active_ptr;
349         zd->frames_since_golden       = xd->frames_since_golden;
350         zd->frames_till_alt_ref_frame   = xd->frames_till_alt_ref_frame;
351         */
352         zd->subpixel_predict         = xd->subpixel_predict;
353         zd->subpixel_predict8x4      = xd->subpixel_predict8x4;
354         zd->subpixel_predict8x8      = xd->subpixel_predict8x8;
355         zd->subpixel_predict16x16    = xd->subpixel_predict16x16;
356         zd->segmentation_enabled     = xd->segmentation_enabled;
357         zd->mb_segement_abs_delta      = xd->mb_segement_abs_delta;
358         vpx_memcpy(zd->segment_feature_data, xd->segment_feature_data, sizeof(xd->segment_feature_data));
359
360         for (i = 0; i < 25; i++)
361         {
362             zd->block[i].dequant = xd->block[i].dequant;
363         }
364     }
365 }
366
367 void vp8cx_init_mbrthread_data(VP8_COMP *cpi,
368                                MACROBLOCK *x,
369                                MB_ROW_COMP *mbr_ei,
370                                int mb_row,
371                                int count
372                               )
373 {
374
375     VP8_COMMON *const cm = & cpi->common;
376     MACROBLOCKD *const xd = & x->e_mbd;
377     int i;
378     (void) mb_row;
379
380     for (i = 0; i < count; i++)
381     {
382         MACROBLOCK *mb = & mbr_ei[i].mb;
383         MACROBLOCKD *mbd = &mb->e_mbd;
384
385         mbd->subpixel_predict        = xd->subpixel_predict;
386         mbd->subpixel_predict8x4     = xd->subpixel_predict8x4;
387         mbd->subpixel_predict8x8     = xd->subpixel_predict8x8;
388         mbd->subpixel_predict16x16   = xd->subpixel_predict16x16;
389 #if CONFIG_RUNTIME_CPU_DETECT
390         mbd->rtcd                   = xd->rtcd;
391 #endif
392         mb->gf_active_ptr            = x->gf_active_ptr;
393
394         mb->vector_range             = 32;
395
396         vpx_memset(mbr_ei[i].segment_counts, 0, sizeof(mbr_ei[i].segment_counts));
397         mbr_ei[i].totalrate = 0;
398
399         mb->partition_info = x->pi + x->e_mbd.mode_info_stride * (i + 1);
400
401         mbd->mode_info_context = cm->mi   + x->e_mbd.mode_info_stride * (i + 1);
402         mbd->mode_info_stride  = cm->mode_info_stride;
403
404         mbd->frame_type = cm->frame_type;
405
406         mbd->frames_since_golden = cm->frames_since_golden;
407         mbd->frames_till_alt_ref_frame = cm->frames_till_alt_ref_frame;
408
409         mb->src = * cpi->Source;
410         mbd->pre = cm->yv12_fb[cm->lst_fb_idx];
411         mbd->dst = cm->yv12_fb[cm->new_fb_idx];
412
413         mb->src.y_buffer += 16 * x->src.y_stride * (i + 1);
414         mb->src.u_buffer +=  8 * x->src.uv_stride * (i + 1);
415         mb->src.v_buffer +=  8 * x->src.uv_stride * (i + 1);
416
417         vp8_build_block_offsets(mb);
418
419         vp8_setup_block_dptrs(mbd);
420
421         vp8_setup_block_ptrs(mb);
422
423         mb->activity_sum = 0;
424
425         mbd->left_context = &cm->left_context;
426         mb->mvc = cm->fc.mvc;
427
428         setup_mbby_copy(&mbr_ei[i].mb, x);
429
430     }
431 }
432
433 void vp8cx_create_encoder_threads(VP8_COMP *cpi)
434 {
435     cpi->b_multi_threaded = 0;
436
437     cpi->processor_core_count = 32; //vp8_get_proc_core_count();
438
439     CHECK_MEM_ERROR(cpi->tplist, vpx_malloc(sizeof(TOKENLIST) * cpi->common.mb_rows));
440
441 #if CONFIG_MULTITHREAD
442
443     if (cpi->processor_core_count > 1 && cpi->oxcf.multi_threaded > 1)
444     {
445         int ithread;
446
447         if (cpi->oxcf.multi_threaded > cpi->processor_core_count)
448             cpi->encoding_thread_count = cpi->processor_core_count - 1;
449         else
450             cpi->encoding_thread_count = cpi->oxcf.multi_threaded - 1;
451
452         CHECK_MEM_ERROR(cpi->h_encoding_thread, vpx_malloc(sizeof(pthread_t) * cpi->encoding_thread_count));
453         CHECK_MEM_ERROR(cpi->h_event_start_encoding, vpx_malloc(sizeof(sem_t) * cpi->encoding_thread_count));
454         CHECK_MEM_ERROR(cpi->mb_row_ei, vpx_memalign(32, sizeof(MB_ROW_COMP) * cpi->encoding_thread_count));
455         vpx_memset(cpi->mb_row_ei, 0, sizeof(MB_ROW_COMP) * cpi->encoding_thread_count);
456         CHECK_MEM_ERROR(cpi->en_thread_data, vpx_malloc(sizeof(ENCODETHREAD_DATA) * cpi->encoding_thread_count));
457         CHECK_MEM_ERROR(cpi->mt_current_mb_col, vpx_malloc(sizeof(*cpi->mt_current_mb_col) * cpi->common.mb_rows));
458
459         //cpi->h_event_main = CreateEvent(NULL, FALSE, FALSE, NULL);
460         sem_init(&cpi->h_event_end_encoding, 0, 0);
461
462         cpi->b_multi_threaded = 1;
463
464         //printf("[VP8:] multi_threaded encoding is enabled with %d threads\n\n", (cpi->encoding_thread_count +1));
465
466         for (ithread = 0; ithread < cpi->encoding_thread_count; ithread++)
467         {
468             ENCODETHREAD_DATA * ethd = &cpi->en_thread_data[ithread];
469
470             //cpi->h_event_mbrencoding[ithread] = CreateEvent(NULL, FALSE, FALSE, NULL);
471             sem_init(&cpi->h_event_start_encoding[ithread], 0, 0);
472             ethd->ithread = ithread;
473             ethd->ptr1 = (void *)cpi;
474             ethd->ptr2 = (void *)&cpi->mb_row_ei[ithread];
475
476             //printf(" call begin thread %d \n", ithread);
477
478             //cpi->h_encoding_thread[ithread] =   (HANDLE)_beginthreadex(
479             //  NULL,           // security
480             //  0,              // stksize
481             //  thread_encoding_proc,
482             //  (&cpi->en_thread_data[ithread]),          // Thread data
483             //  0,
484             //  NULL);
485
486             pthread_create(&cpi->h_encoding_thread[ithread], 0, thread_encoding_proc, ethd);
487         }
488
489     }
490
491 #endif
492 }
493
494 void vp8cx_remove_encoder_threads(VP8_COMP *cpi)
495 {
496 #if CONFIG_MULTITHREAD
497
498     if (cpi->b_multi_threaded)
499     {
500         //shutdown other threads
501         cpi->b_multi_threaded = 0;
502         {
503             int i;
504
505             for (i = 0; i < cpi->encoding_thread_count; i++)
506             {
507                 //SetEvent(cpi->h_event_mbrencoding[i]);
508                 sem_post(&cpi->h_event_start_encoding[i]);
509                 pthread_join(cpi->h_encoding_thread[i], 0);
510
511                 sem_destroy(&cpi->h_event_start_encoding[i]);
512             }
513         }
514
515         sem_destroy(&cpi->h_event_end_encoding);
516
517         //free thread related resources
518         vpx_free(cpi->h_event_start_encoding);
519         vpx_free(cpi->h_encoding_thread);
520         vpx_free(cpi->mb_row_ei);
521         vpx_free(cpi->en_thread_data);
522         vpx_free(cpi->mt_current_mb_col);
523     }
524
525 #endif
526     vpx_free(cpi->tplist);
527 }