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