Android 2.3 Gallery3D添加gif支持——修改代码(三)

来源:互联网 发布:金牌商家网络评选 编辑:程序博客网 时间:2024/05/19 06:14

http://blog.csdn.net/yihongyuelan/article/details/8045748


概要

       前两篇文章:

       《Android 2.3 Gallery3D添加gif支持——概要(一)》

       《Android 2.3 Gallery3D添加gif支持——图片显示(二)》

       看过Gallery3D代码的童鞋都知道,其代码不仅多而且很复杂,因此对于代码这里不会做过于详细的分析,重点是流程。毕竟关键的方法就那么几个,其他修改不外乎为了完善它,仅此而已。

       欢迎转载,请务必注明出处:http://blog.csdn.net/yihongyuelan/

       对于让Android显示gif图片,其实有很多种做法,比如:

       (1). 以Java的方式对gif进行解析并显示。

       在Gallery3D中,当获取到该图片为gif格式时,调用一套单独的解析显示流程。解析包括获取当前gif中每一张图片,以及每一张图片之间的显示间隔等等;显示包括用一个循环的方式让每一张图片。当然我们可以将解析方式以Jar包的方式引入,网上的现成例子有很多。

       (2).以C/C++的方式对gif进行解析并显示。

       Android 2.3 集成了Skia这个强大的图形显示引擎,有多强大呢?(那么那么强大!!o(╯□╰)o还是自己百度吧),Skia是支持对gif解析的。但为什么google没有使用Skia来进行gif解析呢?这是有多方面原因的,Android默认开发都是针对模拟器的,但模拟器的性能大家都知道吧,CPU资源少,内存资源少等等,总的来讲google为了保证模拟器的“正常运行”就没有加入gif的显示。

       回到文章主题,也就是说我们可以通过Skia对gif进行解码,然后修改一下Gallery3D显示逻辑,从而完成gif的显示。这样子不用我说,大家也知道效率比Java高很多倍了吧!!既然能够通过Skia来解析gif图片,自然可以通过类似的方式来改造ImageView等等。

基本框架

       本文采用第二种方案,大致流程如图1所示:


                                                                                     图1

框架解析

       通过图1我们可以知道,我们需要修改的代码包括三个部分,Gallery3D以及Framework中添加接口,最后调用Native方法去解析gif并返回。整个流程看似简单,但要完善整个功能需要修改的文件多达15个啊( ⊙ o ⊙ )!废话不多讲,我们先从APP层的Gallery3D入手。

APP层

       这里所说的APP层,实际上就是com.android.cooliris下的修改。位于:AndroidSource/packages/appa/Gallery3D
       主要思路:Gallery3D是如何显示一张图片的?
       无论是jpeg还是bmp,当我们在Gallery3D中点击缩略图时,它们走的流程应该是一致的,即根据缩略图信息查找到数据库中对应的真实地址并对图片进行解析。因此在Gallery3D需要显示一张图片时,如果我判断到当前的图片类型是gif格式,那么我们让该gif图片走一套单独的显示流程即可完成gif的播放。这套独立的显示流程包括以下几步:
       (1). 检测图片类型,即判断是否是gif图片(isGifImage)。
       (2). 如果是gif图片,那么我需要为播放gif图片做好准备,解析图片(decodeOneFrame)、一张图片显示时长(getFrameDuration)。
       (3). 准备完成之后,需要有播放(playGif)和停止播放(stopGif)。
       (4). 显示完一张gif中的图片之后,需要显示下一张图片(displayNextFrame)。
       整个流程如图2:

                                                                     图2

       单独显示一张图片,最终调用到com/cooliris/media/GridDrawManager.java中的drawFocusItems(),以下代码“+”号表示添加代码,“-”表示删除代码,如下:
[java] view plaincopy
  1. void drawFocusItems(RenderView view, GL11 gl, float zoomValue, boolean slideshowMode, float timeElapsedSinceView) {  
  2.          int selectedSlotIndex = mSelectedSlot;  
  3.          GridDrawables drawables = mDrawables;  
  4.          int firstBufferedVisibleSlot = mBufferedVisibleRange.begin;  
  5.          int lastBufferedVisibleSlot = mBufferedVisibleRange.end;  
  6.          boolean isCameraZAnimating = mCamera.isZAnimating();  
  7. +        //如果不满足gif播放条件则停止播放  
  8. +        boolean playGifMode = false;  
  9.          for (int i = firstBufferedVisibleSlot; i <= lastBufferedVisibleSlot; ++i) {  
  10. +               DisplayItem displayItem = displayItems[(i - firstBufferedVisibleSlot) * GridLayer.MAX_ITEMS_PER_SLOT];  
  11. +               if (i != selectedSlotIndex && displayItem != null) {  
  12. +                displayItem.stopGif();  
  13. +            }  
  14.              if (selectedSlotIndex != Shared.INVALID && (i >= selectedSlotIndex - 2 && i <= selectedSlotIndex + 2)) {  
  15.                  continue;  
  16.              }  
  17. -            DisplayItem displayItem = displayItems[(i - firstBufferedVisibleSlot) * GridLayer.MAX_ITEMS_PER_SLOT];  
  18.              if (displayItem != null) {  
  19.                  displayItem.clearScreennailImage();  
  20.              }  
  21.                  return;  
  22.              }  
  23.              boolean focusItemTextureLoaded = false;  
  24. -            Texture centerTexture = centerDisplayItem.getScreennailImage(view.getContext());  
  25. +            //获取图片纹理信息  
  26. +            Texture centerTexture = centerDisplayItem.getScreennailImage(view);  
  27.              if (centerTexture != null && centerTexture.isLoaded()) {  
  28.                  focusItemTextureLoaded = true;  
  29.              }  
  30.              view.setAlpha(1.0f);  
  31.              gl.glEnable(GL11.GL_BLEND);  
  32.              gl.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE);  
  33. +            int selectedIndexInDrawnArray = (selectedSlotIndex - firstBufferedVisibleSlot)  
  34. +                    * GridLayer.MAX_ITEMS_PER_SLOT;  
  35. +            DisplayItem selectedDisplayItem = displayItems[selectedIndexInDrawnArray];  
  36. +            MediaItem selectedItem = selectedDisplayItem.mItemRef;  
  37. +            if (selectedItem.isGifImage() && !slideshowMode) {  
  38. +                playGifMode = true;  
  39. +                mDisplayGifItem = selectedDisplayItem;  
  40. +            }  
  41.              float backupImageTheta = 0.0f;  
  42.              for (int i = -1; i <= 1; ++i) {  
  43.                  if (slideshowMode && timeElapsedSinceView > 1.0f && i != 0)  
  44.                      continue;  
  45. +                //添加是否是GifMode判断条件  
  46. +                if (playGifMode && i != 0) {  
  47. +                    continue;  
  48. +                }  
  49.                  float viewAspect = camera.mAspectRatio;  
  50.                  int selectedSlotToUse = selectedSlotIndex + i;  
  51.                  if (selectedSlotToUse >= 0 && selectedSlotToUse <= lastBufferedVisibleSlot) {  
  52.                      DisplayItem displayItem = displayItems[indexInDrawnArray];  
  53.                      MediaItem item = displayItem.mItemRef;  
  54.                      final Texture thumbnailTexture = displayItem.getThumbnailImage(view.getContext(), sThumbnailConfig);  
  55. -                    Texture texture = displayItem.getScreennailImage(view.getContext());  
  56. -                    if (isCameraZAnimating && (texture == null || !texture.isLoaded())) {  
  57. +                    //获取下一张图片  
  58. +                    Texture texture = displayItem.getScreennailImage(view);  
  59. +                    Texture nextFrameTexture = displayItem.getNextFrame();  
  60. +                    if (playGifMode) {  
  61. +                        long now = SystemClock.uptimeMillis();  
  62. +                        if ((now - mPreTime) > item.getFrameDuration() && nextFrameTexture != null  
  63. +                                && nextFrameTexture.isLoaded()) {  
  64. +                            item.displayNextFrame();  
  65. +                            mPreTime = now;  
  66. +                        }  
  67. +                        view.requestRender();  
  68. +                    }  
  69. +                    //添加是否是GifMode判断条件  
  70. +                    if (!playGifMode && isCameraZAnimating && (texture == null || !texture.isLoaded())) {  
  71.                          texture = thumbnailTexture;  
  72.                          mSelectedMixRatio.setValue(0f);  
  73.                          mSelectedMixRatio.animateValue(1f, 0.75f, view.getFrameTime());  
  74.                      }  
  75. -                    Texture hiRes = (zoomValue != 1.0f && i == 0 && item.getMediaType() != MediaItem.MEDIA_TYPE_VIDEO) ? displayItem  
  76. +                    //添加是否是GifMode判断条件  
  77. +                    Texture hiRes = (!playGifMode && zoomValue != 1.0f && i == 0 && item.getMediaType() != MediaItem.MEDIA_TYPE_VIDEO) ? displayItem  
  78.                              .getHiResImage(view.getContext())  
  79.                              : null;  
  80.                      if (App.PIXEL_DENSITY > 1.0f) {  
  81.                              }  
  82.                          }  
  83.                          texture = thumbnailTexture;  
  84. -                        if (i == 0) {  
  85. +                        //添加是否是GifMode判断条件  
  86. +                        if (i == 0 && !playGifMode) {  
  87.                              mSelectedMixRatio.setValue(0f);  
  88.                              mSelectedMixRatio.animateValue(1f, 0.75f, view.getFrameTime());  
  89. -                        if (i == 0) {  
  90. +                        //添加是否是GifMode判断条件  
  91. +                        if (i == 0 && !playGifMode) {  
  92.                              mSelectedMixRatio.setValue(0f);  
  93. -                        if (i == 0) {  
  94. -                        if (i == 0) {  
  95. +                        //添加是否是GifMode判断条件  
  96. +                        if (i == 0 && !playGifMode) {  
  97.                              mSelectedMixRatio.setValue(0f);  
  98.                              mSelectedMixRatio.animateValue(1f, 0.75f, view.getFrameTime());  
  99. +                        //判断纹理是否已经加载,如果是则预先解析第二祯图片  
  100. +                        }  
  101. +                    } else if (texture.isLoaded()) {  
  102. +                        if (playGifMode && nextFrameTexture == null) {  
  103. +                            mPreTime = SystemClock.uptimeMillis();  
  104. +                            displayItem.preDecodeNextFrame(view);  
  105.                          }  
  106.                      }  
  107.                      if (mCamera.isAnimating() || slideshowMode) {  
  108.                              continue;  
  109.                          }  
  110.                      }  
  111. -                    int theta = (int) displayItem.getImageTheta();  
  112. +                    //取绝对值  
  113. +                    int theta = Math.abs((int) displayItem.getImageTheta());  
  114.                      // If it is in slideshow mode, we draw the previous item in  
  115.                      // the next item's position.  
  116.                      if (slideshowMode && timeElapsedSinceView < 1.0f && timeElapsedSinceView != 0) {  
  117.                          int vboIndex = i + 1;  
  118.                          float alpha = view.getAlpha();  
  119.                          float selectedMixRatio = mSelectedMixRatio.getValue(view.getFrameTime());  
  120. -                        if (selectedMixRatio != 1f) {  
  121. +                        //添加是否是GifMode判断条件  
  122. +                        if (selectedMixRatio != 1f && !playGifMode) {  
  123.                              texture = thumbnailTexture;  
  124.                              view.setAlpha(alpha * (1.0f - selectedMixRatio));  
  125.                          }  
  126.              view.unbindMixed();  
  127.          }  
  128.      }  

       这就是图2中所表达的gif图片显示逻辑,但整个APP层需要修改的地方有很多,如图3所示:

                                                                                  图3
       (注:这些修改并不是一次完成的,因此有的方法可能并没有使用,但也没有删除,比如MediaItem.java中的decodeNextFrame、startPlay等等,这些方法都是可以删掉的)

       虽然看起来那么复杂,但是我们一定要记清楚原始思路“Gallery3D如何显示一张图片”。通过前面的分析我们知道了大致需要4步,这4步的内容正好添加在MediaItem.java中,我们来看看这几步吧,代码如下:
[java] view plaincopy
  1. +    //判断是否是gif图片  
  2. +    public boolean isGifImage() {  
  3. +        return ("image/gif".equals(mMimeType));  
  4. +    }  
  5. +    //播放gif  
  6. +    public boolean playGif() {  
  7. +        return mPlayGif;  
  8. +    }  
  9. +    //获取播放索引  
  10. +    public int getDisplayIndex() {  
  11. +        return mDisplayIndex;  
  12. +    }  
  13. +    //获取解码索引  
  14. +    public int getDecodeIndex() {  
  15. +        return mDecodeIndex;  
  16. +    }  
  17. +    //获取下一帧图片  
  18. +    public void displayNextFrame() {  
  19. +        if (mGifDecoder != null) {  
  20. +            int count = mGifDecoder.getTotalFrameCount() - 1;  
  21. +            if (mDisplayIndex < count) {  
  22. +                mDisplayIndex++;  
  23. +            } else if (mDisplayIndex == count) {  
  24. +                mDisplayIndex = 0;  
  25. +            }  
  26. +            mTextureNeedChange = true;  
  27. +        }  
  28. +    }  
  29. +    //纹理需要改变  
  30. +    public boolean textureNeedChange() {  
  31. +        return mTextureNeedChange;  
  32. +    }  
  33. +    //纹理已经改变  
  34. +    public void textureChanged() {  
  35. +        mTextureNeedChange = false;  
  36. +    }  
  37. +    //获取gif解码器,通过底层必经之路  
  38. +    public synchronized GifDecoder getGifDecoder(Context context) {  
  39. +        if (mGifDecoder == null) {  
  40. +            InputStream inputStream = null;  
  41. +            ContentResolver cr = context.getContentResolver();  
  42. +            try {  
  43. +                inputStream = cr.openInputStream(Uri.parse(mContentUri));  
  44. +                mGifDecoder = new GifDecoder(inputStream);  
  45. +                inputStream.close();  
  46. +            } catch (FileNotFoundException e) {  
  47. +                // TODO Auto-generated catch block  
  48. +                e.printStackTrace();  
  49. +            } catch (IOException e) {  
  50. +                e.printStackTrace();  
  51. +            }  
  52. +        }  
  53. +        return mGifDecoder;  
  54. +    }  
  55. +    //获取单张图片显示时间  
  56. +    public int getFrameDuration() {  
  57. +        if (mGifDecoder != null) {  
  58. +            return mGifDecoder.getFrameDuration(mDisplayIndex);  
  59. +        }  
  60. +        return Shared.INFINITY;  
  61. +    }  
  62. +    //解析一张图片  
  63. +    public synchronized Bitmap decodeOneFrame() {  
  64. +        Bitmap bitmap = null;  
  65. +        if (mGifDecoder != null) {  
  66. +            int count = mGifDecoder.getTotalFrameCount() - 1;  
  67. +            bitmap = mGifDecoder.getFrameBitmap(mDecodeIndex);  
  68. +            // draw the bitmap to a white canvas  
  69. +            bitmap = Util.whiteBackground(bitmap);  
  70. +            if (mDecodeIndex < count) {  
  71. +                mDecodeIndex++;  
  72. +            } else if (mDecodeIndex == count) {  
  73. +                mDecodeIndex = 0;  
  74. +            }  
  75. +        }  
  76. +        return bitmap;  
  77. +    }  
  78. +    停止播放  
  79. +    public void stopGif() {  
  80. +        if (mGifDecoder != null) {  
  81. +            mGifDecoder.close();  
  82. +            mGifDecoder = null;  
  83. +        }  
  84. +        mPlayGif = false;  
  85. +        mDisplayIndex = 0;  
  86. +        mDecodeIndex = 0;  
  87. +        mTextureNeedChange = false;  
  88. +    }  

Framework层

       说到Framework层,这是里关键的接口,同时起到了穿针引线 承上启下的作用。也就是我们的GifDecoer.java,这是新添加的类,位于AndroidSourceframeworks/base/graphics/java/android/graphics/GifDecoder.java,代码如下:
[java] view plaincopy
  1. package android.graphics;  
  2.   
  3. import java.io.InputStream;  
  4. import java.io.FileInputStream;  
  5. import java.io.BufferedInputStream;  
  6. import android.util.Log;  
  7. import android.graphics.Bitmap;  
  8.   
  9. public class GifDecoder {  
  10.   
  11.     /** 
  12.      * Specify the minimal frame duration in GIF file, unit is ms. 
  13.      * Set as 100, then gif animation hehaves mostly as other gif viewer. 
  14.      */  
  15.     private static final int MINIMAL_DURATION = 100;  
  16.   
  17.     /** 
  18.      * Invalid returned value of some memeber function, such as getWidth() 
  19.      * getTotalFrameCount(), getFrameDuration() 
  20.      */  
  21.     public static final int INVALID_VALUE = 0;  
  22.   
  23.   
  24.     /** 
  25.      * Movie object maitained by GifDecoder, it contains raw GIF info 
  26.      * like graphic control informations, color table, pixel indexes, 
  27.      * called when application is no longer interested in gif info.  
  28.      * It is contains GIF frame bitmap, 8-bits per pixel,  
  29.      * using SkColorTable to specify the colors, which is much 
  30.      * memory efficient than ARGB_8888 config. This is why we 
  31.      * maintain a Movie object rather than a set of ARGB_8888 Bitmaps. 
  32.      */  
  33.     private Movie mMovie;  
  34.       
  35.     /** 
  36.      * Constructor of GifDecoder, which receives InputStream as 
  37.      * parameter. Decode an InputStream into Movie object.  
  38.      * If the InputStream is null, no decoding will be performed 
  39.      * 
  40.      * @param is InputStream representing the file to be decoded. 
  41.      */  
  42.     public GifDecoder(InputStream is) {  
  43.         if (is == null)  
  44.             return;  
  45.         mMovie = Movie.decodeStream(is);  
  46.     }  
  47.   
  48.     public GifDecoder(byte[] data, int offset,int length) {  
  49.         if (data == null)  
  50.             return;  
  51.         mMovie = Movie.decodeByteArray(data, offset, length);  
  52.     }  
  53.   
  54.     /** 
  55.      * Constructor of GifDecoder, which receives file path name as 
  56.      * parameter. Decode a file path into Movie object.  
  57.      * If the specified file name is null, no decoding will be performed 
  58.      * 
  59.      * @param pathName complete path name for the file to be decoded. 
  60.      */  
  61.     public GifDecoder(String pathName) {  
  62.         if (pathName == null)  
  63.             return;  
  64.         mMovie = Movie.decodeFile(pathName);  
  65.     }  
  66.   
  67.     /** 
  68.      * Close gif file, release all informations like frame count, 
  69.      * graphic control informations, color table, pixel indexes, 
  70.      * called when application is no longer interested in gif info.  
  71.      * It will release all the memory mMovie occupies. After close() 
  72.      * is call, GifDecoder should no longer been used. 
  73.      */  
  74.     public synchronized void close(){  
  75.         if (mMovie == null)  
  76.             return;  
  77.         mMovie.closeGif();  
  78.         mMovie = null;  
  79.     }  
  80.   
  81.   
  82.     /** 
  83.      * Get width of images in gif file.  
  84.      * if member mMovie is null, returns INVALID_VALUE 
  85.      * 
  86.      * @return The total frame count of gif file, 
  87.      *         or INVALID_VALUE if the mMovie is null 
  88.      */  
  89.     public synchronized int getWidth() {  
  90.         if (mMovie == null)  
  91.             return INVALID_VALUE;  
  92.         return mMovie.width();  
  93.     }  
  94.   
  95.     /** 
  96.      * Get height of images in gif file.  
  97.      * if member mMovie is null, returns INVALID_VALUE 
  98.      * 
  99.      * @return The total frame count of gif file, 
  100.      *         or INVALID_VALUE if the mMovie is null 
  101.      */  
  102.     public synchronized int getHeight() {  
  103.         if (mMovie == null)  
  104.             return INVALID_VALUE;  
  105.         return mMovie.height();  
  106.     }  
  107.   
  108.     /** 
  109.      * Get total duration of gif file.  
  110.      * if member mMovie is null, returns INVALID_VALUE 
  111.      * 
  112.      * @return The total duration of gif file, 
  113.      *         or INVALID_VALUE if the mMovie is null 
  114.      */  
  115.     public synchronized int getTotalDuration() {  
  116.         if (mMovie == null)  
  117.             return INVALID_VALUE;  
  118.         return mMovie.duration();  
  119.     }  
  120.   
  121.     /** 
  122.      * Get total frame count of gif file.  
  123.      * if member mMovie is null, returns INVALID_VALUE 
  124.      * 
  125.      * @return The total frame count of gif file, 
  126.      *         or INVALID_VALUE if the mMovie is null 
  127.      */  
  128.     public synchronized int getTotalFrameCount() {  
  129.         if (mMovie == null)  
  130.             return INVALID_VALUE;  
  131.         return mMovie.gifTotalFrameCount();  
  132.     }  
  133.   
  134.     /** 
  135.      * Get frame duration specified with frame index of gif file.  
  136.      * if member mMovie is null, returns INVALID_VALUE 
  137.      * 
  138.      * @param frameIndex index of frame interested. 
  139.      * @return The duration of the specified frame, 
  140.      *         or INVALID_VALUE if the mMovie is null 
  141.      */  
  142.     public synchronized int getFrameDuration(int frameIndex) {  
  143.         if (mMovie == null)  
  144.             return INVALID_VALUE;  
  145.         int duration = mMovie.gifFrameDuration(frameIndex);  
  146.         if (duration < MINIMAL_DURATION)  
  147.             duration = MINIMAL_DURATION;  
  148.         return duration;  
  149.     }  
  150.   
  151.     /** 
  152.      * Get frame bitmap specified with frame index of gif file.  
  153.      * if member mMovie is null, returns null 
  154.      * 
  155.      * @param frameIndex index of frame interested. 
  156.      * @return The decoded bitmap, or null if the mMovie is null 
  157.      */  
  158.     public synchronized Bitmap getFrameBitmap(int frameIndex) {  
  159.         if (mMovie == null)  
  160.             return null;  
  161.         return mMovie.gifFrameBitmap(frameIndex);  
  162.     }  
  163.    
  164. }  

       其中都有注释,这里就不细说了。通过查看代码可以知道,实际上我们的GifDecoder调用的是Movie。也就是AndroidSource/frameworks/base/graphics/java/android/graphics/Movie.java。这里为什么调用Movie.java呢?仔细查看可以知道,我们的GifDecoder调用了Movie中的decodeStream方法,但是还有很多通往底层的接口没有打通,怎么办呢?与其另起炉灶不如就借Movie.java的地,直接声明引用Native方法。当然我们是可以自己写一个,不过有现成的干嘛不用呢?Movie.java代码如下:
[java] view plaincopy
  1.  public class Movie {  
  2.      private final int mNativeMovie;  
  3.      public native boolean setTime(int relativeMilliseconds);      
  4.    
  5.      public native void draw(Canvas canvas, float x, float y, Paint paint);  
  6. +    //这里添加我们通往底层的接口  
  7. +    //please see GifDecoder for information  
  8. +    public native int gifFrameDuration(int frameIndex);  
  9. +    public native int gifTotalFrameCount();  
  10. +    public native Bitmap gifFrameBitmap(int frameIndex);  
  11. +    public native void closeGif();  
  12.        
  13.      public void draw(Canvas canvas, float x, float y) {  
  14.          draw(canvas, x, y, null);  
  15.      }  
  16.    
  17. -    public static native Movie decodeStream(InputStream is);  
  18. +    //这里的修改是为了让解码器正常工作  
  19. +  
  20. +    public static Movie decodeStream(InputStream is) {  
  21. +        // we need mark/reset to work properly  
  22. +  
  23. +        if (!is.markSupported()) {  
  24. +            //the size of Buffer is aligned with BufferedInputStream  
  25. +            // used in BitmapFactory of Android default version.  
  26. +            is = new BufferedInputStream(is, 8*1024);  
  27. +        }  
  28. +        is.mark(1024);  
  29. +   
  30. +        return decodeMarkedStream(is);  
  31. +    }  
  32. +  
  33. +//    public static native Movie decodeStream(InputStream is);  
  34. +    private static native Movie decodeMarkedStream(InputStream is);  

       在Framework层中的Java修改就主要涉及到GifDecoder.java和Movie.java,如图4:

                                                                                         图4

Native层

       在Native层中,实际上这里算不上什么层不层的,只是都是C/C++代码,姑且叫之Native层,首先看到AndroidSource/frameworks/base/core/jni/android/graphics/Movie.cpp中的修改,这里面的修改对应的就是Movie.java中的调用的native方法。修改如下:
[java] view plaincopy
  1. +//please see Movie.java for information  
  2. +static int movie_gifFrameDuration(JNIEnv* env, jobject movie, int frameIndex) {  
  3. +    NPE_CHECK_RETURN_ZERO(env, movie);  
  4. +    SkMovie* m = J2Movie(env, movie);  
  5. +//LOGE("Movie:movie_gifFrameDuration: frame number %d, duration is %d", frameIndex,m->getGifFrameDuration(frameIndex));  
  6. +    return m->getGifFrameDuration(frameIndex);  
  7. +}  
  8. +  
  9. +static jobject movie_gifFrameBitmap(JNIEnv* env, jobject movie, int frameIndex) {  
  10. +    NPE_CHECK_RETURN_ZERO(env, movie);  
  11. +    SkMovie* m = J2Movie(env, movie);  
  12. +    int averTimePoint = 0;  
  13. +    int frameDuration = 0;  
  14. +    int frameCount = m->getGifTotalFrameCount();  
  15. +    if (frameIndex < 0 && frameIndex >= frameCount )  
  16. +        return NULL;  
  17. +    m->setCurrFrame(frameIndex);  
  18. +//then we get frameIndex Bitmap (the current frame of movie is frameIndex now)  
  19. +    SkBitmap *createdBitmap = m->createGifFrameBitmap();  
  20. +    SkBitmap *createdBitmap = m->createGifFrameBitmap();  
  21. +    if (createdBitmap != NULL)  
  22. +    {  
  23. +        return GraphicsJNI::createBitmap(env, createdBitmap, false, NULL);  
  24. +    }  
  25. +    else  
  26. +    {  
  27. +        return NULL;  
  28. +    }  
  29. +}  
  30. +  
  31. +static int movie_gifTotalFrameCount(JNIEnv* env, jobject movie) {  
  32. +    NPE_CHECK_RETURN_ZERO(env, movie);  
  33. +    SkMovie* m = J2Movie(env, movie);  
  34. +//LOGE("Movie:movie_gifTotalFrameCount: frame count %d", m->getGifTotalFrameCount());  
  35. +    return m->getGifTotalFrameCount();  
  36. +}  
  37. +  
  38. +static void movie_closeGif(JNIEnv* env, jobject movie) {  
  39. +    NPE_CHECK_RETURN_VOID(env, movie);  
  40. +    SkMovie* m = J2Movie(env, movie);  
  41. +//LOGE("Movie:movie_closeGif()");  
  42. +    delete m;  
  43. +}  
  44. +  
  45. static jobject movie_decodeStream(JNIEnv* env, jobject clazz, jobject istream) {  
  46.                                  
  47.      NPE_CHECK_RETURN_ZERO(env, istream);  
  48.      {   "setTime",  "(I)Z", (void*)movie_setTime  },  
  49.      {   "draw",     "(Landroid/graphics/Canvas;FFLandroid/graphics/Paint;)V",  
  50.                              (void*)movie_draw  },  
  51. -    { "decodeStream""(Ljava/io/InputStream;)Landroid/graphics/Movie;",  
  52. +//please see Movie.java for information  
  53. +    {   "gifFrameDuration",     "(I)I",  
  54. +                            (void*)movie_gifFrameDuration  },  
  55. +    {   "gifFrameBitmap",   "(I)Landroid/graphics/Bitmap;",  
  56. +                            (void*)movie_gifFrameBitmap  },  
  57. +    {   "gifTotalFrameCount",   "()I",  
  58. +                            (void*)movie_gifTotalFrameCount  },  
  59. +    {   "closeGif",   "()V",  
  60. +                            (void*)movie_closeGif  },  
  61. +    { "decodeMarkedStream""(Ljava/io/InputStream;)Landroid/graphics/Movie;",  
  62.                              (void*)movie_decodeStream },  
  63. +//    { "decodeStream", "(Ljava/io/InputStream;)Landroid/graphics/Movie;",  
  64. +//                            (void*)movie_decodeStream },  
  65.      { "decodeByteArray""([BII)Landroid/graphics/Movie;",  
  66.                              (void*)movie_decodeByteArray },  
  67.  };  

       通过以上代码我们可以知道,实际上我又调用到了AndroidSource/external/skia/src/images/SkMovie.cpp以及AndroidSource/external/skia/src/images/SkMovie_gif.cpp中,先来看下SkMovie.cpp中的修改:
[java] view plaincopy
  1. +int SkMovie::getGifFrameDuration(int frameIndex)  
  2. +{  
  3. +    return 0;  
  4. +}  
  5. +  
  6. +int SkMovie::getGifTotalFrameCount()  
  7. +{  
  8. +    return 0;  
  9. +}  
  10. +  
  11. +bool SkMovie::setCurrFrame(int frameIndex)  
  12. +{  
  13. +    return true;  
  14. +}  
  15. +  
  16. +SkBitmap* SkMovie::createGifFrameBitmap()  
  17. +{  
  18. +    //get default bitmap, create a new bitmap and returns.  
  19. +    SkBitmap *copyedBitmap = new SkBitmap();  
  20. +    bool copyDone = false;  
  21. +    if (fNeedBitmap)  
  22. +    {  
  23. +        if (!this->onGetBitmap(&fBitmap))   // failure  
  24. +            fBitmap.reset();  
  25. +{  
  26. +    return 0;  
  27. +}  
  28. +  
  29. +int SkMovie::getGifTotalFrameCount()  
  30. +{  
  31. +    return 0;  
  32. +}  
  33. +  
  34. +bool SkMovie::setCurrFrame(int frameIndex)  
  35. +{  
  36. +    return true;  
  37. +}  
  38. +}  
  39. +  
  40. +SkBitmap* SkMovie::createGifFrameBitmap()  
  41. +{  
  42. +    //get default bitmap, create a new bitmap and returns.  
  43. +    SkBitmap *copyedBitmap = new SkBitmap();  
  44. +    bool copyDone = false;  
  45. +    if (fNeedBitmap)  
  46. +    {  
  47. +        if (!this->onGetBitmap(&fBitmap))   // failure  
  48. +            fBitmap.reset();  
  49. +    }  
  50. +    //now create a new bitmap from fBitmap  
  51. +    if (fBitmap.canCopyTo(SkBitmap::kARGB_8888_Config) )  
  52. +    {  
  53. +//LOGE("SkMovie:createGifFrameBitmap:fBitmap can copy to 8888 config, then copy...");  
  54. +        copyDone = fBitmap.copyTo(copyedBitmap, SkBitmap::kARGB_8888_Config);  
  55. +    }  
  56. +    else  
  57. +    {  
  58. +        copyDone = false;  
  59. +//LOGE("SkMovie:createGifFrameBitmap:fBitmap can NOT copy to 8888 config");  
  60. +    }  
  61. +  
  62. +    if (copyDone)  
  63. +    {  
  64. +        return copyedBitmap;  
  65. +    }  
  66. +    else  
  67. +    {  
  68. +        return NULL;  
  69. +    }  
  70. +}  

       接下来是针对SkMovie_gif.cpp的修改(因为平台原因,这里直接贴代码),代码如下:
[java] view plaincopy
  1. #include "SkMovie.h"  
  2. #include "SkColor.h"  
  3. #include "SkColorPriv.h"  
  4. #include "SkStream.h"  
  5. #include "SkTemplates.h"  
  6. #include "SkUtils.h"  
  7.   
  8. #include <stdlib.h>  
  9. #include <stdio.h>  
  10. #include <string.h>  
  11. #include "gif_lib.h"  
  12.   
  13. #include "utils/Log.h"  
  14.   
  15. class SkGIFMovie : public SkMovie {  
  16. public:  
  17.     SkGIFMovie(SkStream* stream);  
  18.     virtual ~SkGIFMovie();  
  19.   
  20. protected:  
  21.     virtual bool onGetInfo(Info*);  
  22.     virtual bool onSetTime(SkMSec);  
  23.     virtual bool onGetBitmap(SkBitmap*);  
  24.   
  25. //please see Movie.cpp for information  
  26.     virtual int getGifFrameDuration(int frameIndex);  
  27.     virtual int getGifTotalFrameCount();  
  28.     virtual bool setCurrFrame(int frameIndex);  
  29. private:  
  30.     bool checkGifStream(SkStream* stream);  
  31.     bool getWordFromStream(SkStream* stream,int* word);  
  32.     bool getRecordType(SkStream* stream,GifRecordType* Type);  
  33.     bool checkImageDesc(SkStream* stream,char* buf);  
  34.     bool skipExtension(SkStream* stream,char* buf);  
  35.     bool skipComment(SkStream* stream,char* buf);  
  36.     bool skipGraphics(SkStream* stream,char* buf);  
  37.     bool skipPlaintext(SkStream* stream,char* buf);  
  38.     bool skipApplication(SkStream* stream,char* buf);  
  39.     bool skipSubblocksWithTerminator(SkStream* stream,char* buf);  
  40.       
  41. private:  
  42.     GifFileType* fGIF;  
  43.     int fCurrIndex;  
  44.     int fLastDrawIndex;  
  45.     SkBitmap fBackup;  
  46. };  
  47.   
  48. static int Decode(GifFileType* fileType, GifByteType* out, int size) {  
  49.     SkStream* stream = (SkStream*) fileType->UserData;  
  50.     return (int) stream->read(out, size);  
  51. }  
  52.   
  53. SkGIFMovie::SkGIFMovie(SkStream* stream)  
  54. {  
  55.     int streamLength = stream->getLength();  
  56.     //if length of SkStream is below zero, no need for further parsing  
  57.     if (streamLength <= 0) {  
  58.         LOGE("SkGIFMovie:SkGIFMovie: GIF source file length is below 0");  
  59.         return;  
  60.     }  
  61.   
  62.     //allocate a buffer to hold content of SkStream  
  63.     void * streamBuffer = malloc(streamLength+1);  
  64.     if (streamBuffer == 0) {  
  65.         LOGE("SkGIFMovie:SkGIFMovie: malloc Memory stream buffer failed");  
  66.         return;  
  67.     }  
  68.   
  69.     //Fetch SkStream content into buffer  
  70.     if (streamLength != stream->read(streamBuffer, stream->getLength())) {  
  71.         LOGE("SkGIFMovie:SkGIFMovie: read GIF source to Memory Buffer failed");  
  72.         free(streamBuffer);  
  73.         return;  
  74.     }  
  75.   
  76.     //we wrap stream with SkmemoryStream, cause  
  77.     //its rewind does not make mark on InputStream be  
  78.     //invalid.  
  79.     SkStream* memStream = new SkMemoryStream(streamBuffer,streamLength);  
  80.     bool bRewindable = memStream->rewind();  
  81.     if (bRewindable)  
  82.     {  
  83.         //check if GIF file is valid to decode  
  84.         bool bGifValid = checkGifStream(memStream);  
  85.         if (! bGifValid)  
  86.         {  
  87.             free(streamBuffer);  
  88.             fGIF = NULL;  
  89.             return;  
  90.         }  
  91.         //GIF file stream seems to be OK,   
  92.         // rewind stream for gif decoding  
  93.         memStream->rewind();  
  94.     }  
  95.   
  96.     fGIF = DGifOpen( memStream, Decode );  
  97.     if (NULL == fGIF) {  
  98.         free(streamBuffer);  
  99.         return;  
  100.     }  
  101.   
  102.     if (DGifSlurp(fGIF) != GIF_OK)  
  103.     {  
  104.         DGifCloseFile(fGIF);  
  105.         fGIF = NULL;  
  106.     }  
  107.     fCurrIndex = -1;  
  108.     fLastDrawIndex = -1;  
  109.   
  110.     //release stream buffer when decoding is done.  
  111.     free(streamBuffer);  
  112. }  
  113.   
  114. SkGIFMovie::~SkGIFMovie()  
  115. {  
  116.     if (fGIF)  
  117.         DGifCloseFile(fGIF);  
  118. }  
  119.   
  120. static SkMSec savedimage_duration(const SavedImage* image)  
  121. {  
  122.     for (int j = 0; j < image->ExtensionBlockCount; j++)  
  123.     {  
  124.         if (image->ExtensionBlocks[j].Function == GRAPHICS_EXT_FUNC_CODE)  
  125.         {  
  126.             int size = image->ExtensionBlocks[j].ByteCount;  
  127.             SkASSERT(size >= 4);  
  128.             const uint8_t* b = (const uint8_t*)image->ExtensionBlocks[j].Bytes;  
  129.             return ((b[2] << 8) | b[1]) * 10;  
  130.         }  
  131.     }  
  132.     return 0;  
  133. }  
  134.   
  135. int SkGIFMovie::getGifFrameDuration(int frameIndex)  
  136. {  
  137.     //for wrong frame index, return 0  
  138.     if (frameIndex < 0 || NULL == fGIF || frameIndex >= fGIF->ImageCount)  
  139.         return 0;  
  140.     return savedimage_duration(&fGIF->SavedImages[frameIndex]);  
  141. }  
  142.   
  143. int SkGIFMovie::getGifTotalFrameCount()  
  144. {  
  145.     //if fGIF is not valid, return 0  
  146.     if (NULL == fGIF)  
  147.         return 0;  
  148.     return fGIF->ImageCount < 0 ? 0 : fGIF->ImageCount;  
  149. }  
  150.   
  151. bool SkGIFMovie::setCurrFrame(int frameIndex)  
  152. {  
  153.     if (NULL == fGIF)  
  154.         return false;  
  155.   
  156.     if (frameIndex >= 0 && frameIndex < fGIF->ImageCount)  
  157.         fCurrIndex = frameIndex;  
  158.     else  
  159.         fCurrIndex = 0;  
  160.     return true;  
  161. }  
  162.   
  163. bool SkGIFMovie::getWordFromStream(SkStream* stream,int* word)  
  164. {  
  165.     unsigned char buf[2];  
  166.   
  167.     if (stream->read(buf, 2) != 2) {  
  168.         LOGE("SkGIFMovie:getWordFromStream: read from stream failed");  
  169.         return false;  
  170.     }  
  171.   
  172.     *word = (((unsigned int)buf[1]) << 8) + buf[0];  
  173.     return true;  
  174. }  
  175.   
  176. bool SkGIFMovie::getRecordType(SkStream* stream,GifRecordType* Type)  
  177. {  
  178.     unsigned char buf;  
  179.     //read a record type to buffer  
  180.     if (stream->read(&buf, 1) != 1) {  
  181.         LOGE("SkGIFMovie:getRecordType: read from stream failed");  
  182.         return false;  
  183.     }  
  184.     //identify record type  
  185.     switch (buf) {  
  186.       case ',':  
  187.           *Type = IMAGE_DESC_RECORD_TYPE;  
  188.           break;  
  189.       case '!':  
  190.           *Type = EXTENSION_RECORD_TYPE;  
  191.           break;  
  192.       case ';':  
  193.           *Type = TERMINATE_RECORD_TYPE;  
  194.           break;  
  195.       default:  
  196.           *Type = UNDEFINED_RECORD_TYPE;  
  197.           LOGE("SkGIFMovie:getRecordType: wrong gif record type");  
  198.           return false;  
  199.     }  
  200.     return true;  
  201. }  
  202.   
  203. /****************************************************************************** 
  204.  * calculate all image frame count without decode image frame. 
  205.  * SkStream associated with GifFile and GifFile state is not 
  206.  * affected 
  207.  *****************************************************************************/  
  208. bool SkGIFMovie::checkGifStream(SkStream* stream)  
  209. {  
  210.     char buf[16];  
  211.     int screenWidth, screenHeight;  
  212.     int BitsPerPixel = 0;  
  213.     int frameCount = 0;  
  214.     GifRecordType RecordType;  
  215.   
  216.     //maximum stream length is set to be 10M, if the stream is   
  217.     //larger than that, no further action is needed  
  218.     size_t length = stream->getLength();  
  219.     if (length > 10*1024*1024) {  
  220.         LOGE("SkGIFMovie:checkGifStream: stream length larger than 10M");  
  221.         return false;  
  222.     }  
  223.   
  224.     if (GIF_STAMP_LEN != stream->read(buf, GIF_STAMP_LEN)) {  
  225.         LOGE("SkGIFMovie:checkGifStream: read GIF STAMP failed");  
  226.         return false;  
  227.     }  
  228.   
  229.     //Check whether the first three charactar is "GIF", version   
  230.     // number is ignored.  
  231.     buf[GIF_STAMP_LEN] = 0;  
  232.     if (strncmp(GIF_STAMP, buf, GIF_VERSION_POS) != 0) {  
  233.         LOGE("SkGIFMovie:checkGifStream: check GIF stamp failed");  
  234.         return false;  
  235.     }  
  236.   
  237.     //read screen width and height from stream  
  238.     screenWidth = 0;  
  239.     screenHeight = 0;  
  240.     if (! getWordFromStream(stream,&screenWidth) ||  
  241.         ! getWordFromStream(stream,&screenHeight)) {  
  242.         LOGE("SkGIFMovie:checkGifStream: get screen dimension failed");  
  243.         return false;  
  244.     }  
  245.   
  246.     //check whether screen dimension is too large  
  247.     //maximum pixels in a single frame is constrained to 1.5M  
  248.     //which is aligned withSkImageDecoder_libgif.cpp  
  249.     if (screenWidth*screenHeight > 1536*1024) {  
  250.         LOGE("SkGIFMovie:checkGifStream: screen dimension is larger than 1.5M");  
  251.         return false;  
  252.     }  
  253.   
  254.     //read screen color resolution and color map information  
  255.     if (3 != stream->read(buf, 3)) {  
  256.         LOGE("SkGIFMovie:checkGifStream: read color info failed");  
  257.         return false;  
  258.     }  
  259.     BitsPerPixel = (buf[0] & 0x07) + 1;  
  260.     if (buf[0] & 0x80) {      
  261.         //If we have global color table, skip it  
  262.         unsigned int colorTableBytes = (unsigned)(1 << BitsPerPixel) * 3;  
  263.         if (colorTableBytes != stream->skip(colorTableBytes)) {  
  264.             LOGE("SkGIFMovie:checkGifStream: skip global color table failed");  
  265.             return false;  
  266.         }  
  267.     } else {  
  268.     }  
  269. //DGifOpen is over, now for DGifSlurp  
  270.     do {  
  271.         if (getRecordType(stream, &RecordType) == false)  
  272.             return false;  
  273.   
  274.         switch (RecordType) {  
  275.           case IMAGE_DESC_RECORD_TYPE:  
  276.               if (checkImageDesc(stream,buf) == false)  
  277.                   return false;  
  278.               frameCount ++;  
  279.               if (1 != stream->skip(1)) {  
  280.                   LOGE("SkGIFMovie:checkGifStream: skip code size failed");  
  281.                   return false;  
  282.               }  
  283.               if (skipSubblocksWithTerminator(stream,buf) == false) {  
  284.                   LOGE("SkGIFMovie:checkGifStream: skip compressed image data failed");  
  285.                   return false;  
  286.               }  
  287.               break;  
  288.   
  289.           case EXTENSION_RECORD_TYPE:  
  290.               if (skipExtension(stream,buf) == false) {  
  291.                   LOGE("SkGIFMovie:checkGifStream: skip extensions failed");  
  292.                   return false;  
  293.               }  
  294.               break;  
  295.   
  296.           case TERMINATE_RECORD_TYPE:  
  297.               break;  
  298.   
  299.           default:    /* Should be trapped by DGifGetRecordType */  
  300.               break;  
  301.         }  
  302.     } while (RecordType != TERMINATE_RECORD_TYPE);  
  303.   
  304.     //maximum pixels in all gif frames is constrained to 5M  
  305.     //although each frame has its own dimension, we estimate the total  
  306.     //pixels which the decoded gif file had be screen dimension multiply  
  307.     //total image count, this should be the worst case  
  308.     if (screenWidth * screenHeight * frameCount > 1024*1024*5) {  
  309.         LOGE("SkGIFMovie:checkGifStream: total pixels is larger than 5M");  
  310.         return false;  
  311.     }  
  312.   
  313.     return true;  
  314. }  
  315.   
  316. bool SkGIFMovie::checkImageDesc(SkStream* stream,char* buf)  
  317. {  
  318.     int imageWidth,imageHeight;  
  319.     int BitsPerPixel;  
  320.     if (4 != stream->skip(4)) {  
  321.         LOGE("SkGIFMovie:getImageDesc: skip image left-top position");  
  322.         return false;  
  323.     }  
  324.     if (! getWordFromStream(stream,&imageWidth)||  
  325.         ! getWordFromStream(stream,&imageHeight)) {  
  326.         LOGE("SkGIFMovie:getImageDesc: read image width & height");  
  327.         return false;  
  328.     }  
  329.     if (1 != stream->read(buf, 1)) {  
  330.         LOGE("SkGIFMovie:getImageDesc: read image info failed");  
  331.         return false;  
  332.     }  
  333.   
  334.     BitsPerPixel = (buf[0] & 0x07) + 1;  
  335.     if (buf[0] & 0x80) {      
  336.         //If this image have local color map, skip it  
  337.         unsigned int colorTableBytes = (unsigned)(1 << BitsPerPixel) * 3;  
  338.         if (colorTableBytes != stream->skip(colorTableBytes)) {  
  339.             LOGE("SkGIFMovie:getImageDesc: skip global color table failed");  
  340.             return false;  
  341.         }  
  342.     } else {  
  343.     }  
  344.     return true;  
  345. }  
  346.   
  347.   
  348. bool SkGIFMovie::skipExtension(SkStream* stream,char* buf)  
  349. {  
  350.     int imageWidth,imageHeight;  
  351.     int BitsPerPixel;  
  352.     if (1 != stream->read(buf, 1)) {  
  353.         LOGE("SkGIFMovie:skipExtension: read extension type failed");  
  354.         return false;  
  355.     }  
  356.     switch (buf[0]) {  
  357.       case COMMENT_EXT_FUNC_CODE:  
  358.           if (skipComment(stream,buf)==false) {  
  359.               LOGE("SkGIFMovie:skipExtension: skip comment failed");  
  360.               return false;  
  361.           }  
  362.           break;  
  363.       case GRAPHICS_EXT_FUNC_CODE:  
  364.           if (skipGraphics(stream,buf)==false) {  
  365.               LOGE("SkGIFMovie:skipExtension: skip graphics failed");  
  366.               return false;  
  367.           }  
  368.           break;  
  369.       case PLAINTEXT_EXT_FUNC_CODE:  
  370.           if (skipPlaintext(stream,buf)==false) {  
  371.               LOGE("SkGIFMovie:skipExtension: skip plaintext failed");  
  372.               return false;  
  373.           }  
  374.           break;  
  375.       case APPLICATION_EXT_FUNC_CODE:  
  376.           if (skipApplication(stream,buf)==false) {  
  377.               LOGE("SkGIFMovie:skipExtension: skip application failed");  
  378.               return false;  
  379.           }  
  380.           break;  
  381.       default:  
  382.           LOGE("SkGIFMovie:skipExtension: wrong gif extension type");  
  383.           return false;  
  384.     }  
  385.     return true;  
  386. }  
  387.   
  388. bool SkGIFMovie::skipComment(SkStream* stream,char* buf)  
  389. {  
  390.      return skipSubblocksWithTerminator(stream,buf);  
  391. }  
  392.   
  393. bool SkGIFMovie::skipGraphics(SkStream* stream,char* buf)  
  394. {  
  395.      return skipSubblocksWithTerminator(stream,buf);  
  396. }  
  397.   
  398. bool SkGIFMovie::skipPlaintext(SkStream* stream,char* buf)  
  399. {  
  400.      return skipSubblocksWithTerminator(stream,buf);  
  401. }  
  402.   
  403. bool SkGIFMovie::skipApplication(SkStream* stream,char* buf)  
  404. {  
  405.      return skipSubblocksWithTerminator(stream,buf);  
  406. }  
  407.   
  408. bool SkGIFMovie::skipSubblocksWithTerminator(SkStream* stream,char* buf)  
  409. {  
  410.     do {//skip the whole compressed image data.  
  411.         //read sub-block size  
  412.         if (1 != stream->read(buf,1)) {  
  413.             LOGE("SkGIFMovie:skipSubblocksWithTerminator: read sub block size failed");  
  414.             return false;  
  415.         }  
  416.         if (buf[0] > 0) {  
  417.             if (buf[0] != stream->skip(buf[0])) {  
  418.                 LOGE("SkGIFMovie:skipSubblocksWithTerminator: skip sub block failed");  
  419.                 return false;  
  420.             }  
  421.         }  
  422.     } while(buf[0]!=0);  
  423.     return true;  
  424. }  
  425.   
  426. bool SkGIFMovie::onGetInfo(Info* info)  
  427. {  
  428.     if (NULL == fGIF)  
  429.         return false;  
  430.   
  431.     SkMSec dur = 0;  
  432.     for (int i = 0; i < fGIF->ImageCount; i++)  
  433.         dur += savedimage_duration(&fGIF->SavedImages[i]);  
  434.   
  435.     info->fDuration = dur;  
  436.     info->fWidth = fGIF->SWidth;  
  437.     info->fHeight = fGIF->SHeight;  
  438.     info->fIsOpaque = false;  
  439.     return true;  
  440. }  
  441.   
  442. bool SkGIFMovie::onSetTime(SkMSec time)  
  443. {  
  444.     if (NULL == fGIF)  
  445.         return false;  
  446.   
  447.     SkMSec dur = 0;  
  448.     for (int i = 0; i < fGIF->ImageCount; i++)  
  449.     {  
  450.         dur += savedimage_duration(&fGIF->SavedImages[i]);  
  451.         if (dur >= time)  
  452.         {  
  453.             fCurrIndex = i;  
  454.             return fLastDrawIndex != fCurrIndex;  
  455.         }  
  456.     }  
  457.     fCurrIndex = fGIF->ImageCount - 1;  
  458.     return true;  
  459. }  
  460.   
  461. static void copyLine(uint32_t* dst, const unsigned char* src, const ColorMapObject* cmap,  
  462.                      int transparent, int width)  
  463. {  
  464.     for (; width > 0; width--, src++, dst++) {  
  465.         if (*src != transparent) {  
  466.             const GifColorType& col = cmap->Colors[*src];  
  467.             *dst = SkPackARGB32(0xFF, col.Red, col.Green, col.Blue);  
  468.         }  
  469.     }  
  470. }  
  471.   
  472. static void copyInterlaceGroup(SkBitmap* bm, const unsigned char*& src,  
  473.                                const ColorMapObject* cmap, int transparent, int copyWidth,  
  474.                                int copyHeight, const GifImageDesc& imageDesc, int rowStep,  
  475.                                int startRow)  
  476. {  
  477.     int row;  
  478.     // every 'rowStep'th row, starting with row 'startRow'  
  479.     for (row = startRow; row < copyHeight; row += rowStep) {  
  480.         uint32_t* dst = bm->getAddr32(imageDesc.Left, imageDesc.Top + row);  
  481.         copyLine(dst, src, cmap, transparent, copyWidth);  
  482.         src += imageDesc.Width;  
  483.     }  
  484.   
  485.     // pad for rest height  
  486.     src += imageDesc.Width * ((imageDesc.Height - row + rowStep - 1) / rowStep);  
  487. }  
  488.   
  489. static void blitInterlace(SkBitmap* bm, const SavedImage* frame, const ColorMapObject* cmap,  
  490.                           int transparent)  
  491. {  
  492.     int width = bm->width();  
  493.     int height = bm->height();  
  494.     GifWord copyWidth = frame->ImageDesc.Width;  
  495.     if (frame->ImageDesc.Left + copyWidth > width) {  
  496.         copyWidth = width - frame->ImageDesc.Left;  
  497.     }  
  498.   
  499.     GifWord copyHeight = frame->ImageDesc.Height;  
  500.     if (frame->ImageDesc.Top + copyHeight > height) {  
  501.         copyHeight = height - frame->ImageDesc.Top;  
  502.     }  
  503.   
  504.     // deinterlace  
  505.     const unsigned char* src = (unsigned char*)frame->RasterBits;  
  506.   
  507.     // group 1 - every 8th row, starting with row 0  
  508.     copyInterlaceGroup(bm, src, cmap, transparent, copyWidth, copyHeight, frame->ImageDesc, 80);  
  509.   
  510.     // group 2 - every 8th row, starting with row 4  
  511.     copyInterlaceGroup(bm, src, cmap, transparent, copyWidth, copyHeight, frame->ImageDesc, 84);  
  512.   
  513.     // group 3 - every 4th row, starting with row 2  
  514.     copyInterlaceGroup(bm, src, cmap, transparent, copyWidth, copyHeight, frame->ImageDesc, 42);  
  515.   
  516.     copyInterlaceGroup(bm, src, cmap, transparent, copyWidth, copyHeight, frame->ImageDesc, 21);  
  517. }  
  518.   
  519. static void blitNormal(SkBitmap* bm, const SavedImage* frame, const ColorMapObject* cmap,  
  520.                        int transparent)  
  521. {  
  522.     int width = bm->width();  
  523.     int height = bm->height();  
  524.     const unsigned char* src = (unsigned char*)frame->RasterBits;  
  525.     uint32_t* dst = bm->getAddr32(frame->ImageDesc.Left, frame->ImageDesc.Top);  
  526.     GifWord copyWidth = frame->ImageDesc.Width;  
  527.     if (frame->ImageDesc.Left + copyWidth > width) {  
  528.         copyWidth = width - frame->ImageDesc.Left;  
  529.     }  
  530.   
  531.     GifWord copyHeight = frame->ImageDesc.Height;  
  532.     if (frame->ImageDesc.Top + copyHeight > height) {  
  533.         copyHeight = height - frame->ImageDesc.Top;  
  534.     }  
  535.   
  536.     int srcPad, dstPad;  
  537.     dstPad = width - copyWidth;  
  538.     srcPad = frame->ImageDesc.Width - copyWidth;  
  539.     for (; copyHeight > 0; copyHeight--) {  
  540.         copyLine(dst, src, cmap, transparent, copyWidth);  
  541.         src += frame->ImageDesc.Width;  
  542.         dst += width;  
  543.     }  
  544. }  
  545.   
  546. static void fillRect(SkBitmap* bm, GifWord left, GifWord top, GifWord width, GifWord height,  
  547.                      uint32_t col)  
  548. {  
  549.     int bmWidth = bm->width();  
  550.     int bmHeight = bm->height();  
  551.     uint32_t* dst = bm->getAddr32(left, top);  
  552.     GifWord copyWidth = width;  
  553.     if (left + copyWidth > bmWidth) {  
  554.         copyWidth = bmWidth - left;  
  555.     }  
  556.   
  557.     GifWord copyHeight = height;  
  558.     if (top + copyHeight > bmHeight) {  
  559.         copyHeight = bmHeight - top;  
  560.     }  
  561.   
  562.     for (; copyHeight > 0; copyHeight--) {  
  563.         sk_memset32(dst, col, copyWidth);  
  564.         dst += bmWidth;  
  565.     }  
  566. }  
  567.   
  568. static void drawFrame(SkBitmap* bm, const SavedImage* frame, const ColorMapObject* cmap)  
  569. {  
  570.     int transparent = -1;  
  571.   
  572.     for (int i = 0; i < frame->ExtensionBlockCount; ++i) {  
  573.         ExtensionBlock* eb = frame->ExtensionBlocks + i;  
  574.         if (eb->Function == GRAPHICS_EXT_FUNC_CODE &&  
  575.             eb->ByteCount == 4) {  
  576.             bool has_transparency = ((eb->Bytes[0] & 1) == 1);  
  577.             if (has_transparency) {  
  578.                 transparent = (unsigned char)eb->Bytes[3];  
  579.             }  
  580.         }  
  581.     }  
  582.   
  583.     if (frame->ImageDesc.ColorMap != NULL) {  
  584.         // use local color table  
  585.         cmap = frame->ImageDesc.ColorMap;  
  586.     }  
  587.   
  588.     if (cmap == NULL || cmap->ColorCount != (1 << cmap->BitsPerPixel)) {  
  589.         SkASSERT(!"bad colortable setup");  
  590.         return;  
  591.     }  
  592.   
  593.     if (frame->ImageDesc.Interlace) {  
  594.         blitInterlace(bm, frame, cmap, transparent);  
  595.     } else {  
  596.         blitNormal(bm, frame, cmap, transparent);  
  597.     }  
  598. }  
  599.   
  600. static bool checkIfWillBeCleared(const SavedImage* frame)  
  601. {  
  602.     for (int i = 0; i < frame->ExtensionBlockCount; ++i) {  
  603.         ExtensionBlock* eb = frame->ExtensionBlocks + i;  
  604.         if (eb->Function == GRAPHICS_EXT_FUNC_CODE &&  
  605.             eb->ByteCount == 4) {  
  606.             // check disposal method  
  607.             int disposal = ((eb->Bytes[0] >> 2) & 7);  
  608.             if (disposal == 2 || disposal == 3) {  
  609.                 return true;  
  610.             }  
  611.         }  
  612.     }  
  613.     return false;  
  614. }  
  615.   
  616. static void getTransparencyAndDisposalMethod(const SavedImage* frame, bool* trans, int* disposal)  
  617. {  
  618.     *trans = false;  
  619.     *disposal = 0;  
  620.     for (int i = 0; i < frame->ExtensionBlockCount; ++i) {  
  621.         ExtensionBlock* eb = frame->ExtensionBlocks + i;  
  622.         if (eb->Function == GRAPHICS_EXT_FUNC_CODE &&  
  623.             eb->ByteCount == 4) {  
  624.             *trans = ((eb->Bytes[0] & 1) == 1);  
  625.             *disposal = ((eb->Bytes[0] >> 2) & 7);  
  626.         }  
  627.     }  
  628. }  
  629.   
  630. // return true if area of 'target' is completely covers area of 'covered'  
  631. static bool checkIfCover(const SavedImage* target, const SavedImage* covered)  
  632. {  
  633.     if (target->ImageDesc.Left <= covered->ImageDesc.Left  
  634.         && covered->ImageDesc.Left + covered->ImageDesc.Width <=  
  635.                target->ImageDesc.Left + target->ImageDesc.Width  
  636.         && target->ImageDesc.Top <= covered->ImageDesc.Top  
  637.         && covered->ImageDesc.Top + covered->ImageDesc.Height <=  
  638.                target->ImageDesc.Top + target->ImageDesc.Height) {  
  639.         return true;  
  640.     }  
  641.     return false;  
  642. }  
  643.   
  644. static void disposeFrameIfNeeded(SkBitmap* bm, const SavedImage* cur, const SavedImage* next,  
  645.                                  SkBitmap* backup, SkColor color)  
  646. {  
  647.     // We can skip disposal process if next frame is not transparent  
  648.     // and completely covers current area  
  649.     bool curTrans;  
  650.     int curDisposal;  
  651.     getTransparencyAndDisposalMethod(cur, &curTrans, &curDisposal);  
  652.     bool nextTrans;  
  653.     int nextDisposal;  
  654.     getTransparencyAndDisposalMethod(next, &nextTrans, &nextDisposal);  
  655.     if ((curDisposal == 2 || curDisposal == 3)  
  656.         && (nextTrans || !checkIfCover(next, cur))) {  
  657.         switch (curDisposal) {  
  658.         // restore to background color  
  659.         // -> 'background' means background under this image.  
  660.         case 2:  
  661.             fillRect(bm, cur->ImageDesc.Left, cur->ImageDesc.Top,  
  662.                      cur->ImageDesc.Width, cur->ImageDesc.Height,  
  663.                      color);  
  664.             break;  
  665.   
  666.         // restore to previous  
  667.         case 3:  
  668.             bm->swap(*backup);  
  669.             break;  
  670.         }  
  671.     }  
  672.   
  673.     // Save current image if next frame's disposal method == 3  
  674.     if (nextDisposal == 3) {  
  675.         const uint32_t* src = bm->getAddr32(00);  
  676.         uint32_t* dst = backup->getAddr32(00);  
  677.         int cnt = bm->width() * bm->height();  
  678.         memcpy(dst, src, cnt*sizeof(uint32_t));  
  679.     }  
  680. }  
  681.   
  682. bool SkGIFMovie::onGetBitmap(SkBitmap* bm)  
  683. {  
  684.     const GifFileType* gif = fGIF;  
  685.     if (NULL == gif)  
  686.         return false;  
  687.   
  688.     if (gif->ImageCount < 1) {  
  689.         return false;  
  690.     }  
  691.   
  692.     const int width = gif->SWidth;  
  693.     const int height = gif->SHeight;  
  694.     if (width <= 0 || height <= 0) {  
  695.         return false;  
  696.     }  
  697.   
  698.     // no need to draw  
  699.     if (fLastDrawIndex >= 0 && fLastDrawIndex == fCurrIndex) {  
  700.         return true;  
  701.     }  
  702.   
  703.     int startIndex = fLastDrawIndex + 1;  
  704.     if (fLastDrawIndex < 0 || !bm->readyToDraw()) {  
  705.         // first time  
  706.   
  707.         startIndex = 0;  
  708.   
  709.         // create bitmap  
  710.         bm->setConfig(SkBitmap::kARGB_8888_Config, width, height, 0);  
  711.         if (!bm->allocPixels(NULL)) {  
  712.             return false;  
  713.         }  
  714.         // create bitmap for backup  
  715.         fBackup.setConfig(SkBitmap::kARGB_8888_Config, width, height, 0);  
  716.         if (!fBackup.allocPixels(NULL)) {  
  717.             return false;  
  718.         }  
  719.     } else if (startIndex > fCurrIndex) {  
  720.         // rewind to 1st frame for repeat  
  721.         startIndex = 0;  
  722.     }  
  723.   
  724.     int lastIndex = fCurrIndex;  
  725.     if (lastIndex < 0) {  
  726.         // first time  
  727.         lastIndex = 0;  
  728.     } else if (lastIndex > fGIF->ImageCount - 1) {  
  729.         // this block must not be reached.  
  730.         lastIndex = fGIF->ImageCount - 1;  
  731.     }  
  732.   
  733.     SkColor bgColor = SkPackARGB32(0000);  
  734.     if (gif->SColorMap != NULL) {  
  735.         const GifColorType& col = gif->SColorMap->Colors[fGIF->SBackGroundColor];  
  736.         bgColor = SkColorSetARGB(0xFF, col.Red, col.Green, col.Blue);  
  737.     }  
  738.   
  739.     static SkColor paintingColor = SkPackARGB32(0000);  
  740.     // draw each frames - not intelligent way  
  741.     for (int i = startIndex; i <= lastIndex; i++) {  
  742.         const SavedImage* cur = &fGIF->SavedImages[i];  
  743.         if (i == 0) {  
  744.             bool trans;  
  745.             int disposal;  
  746.             getTransparencyAndDisposalMethod(cur, &trans, &disposal);  
  747.             if (!trans && gif->SColorMap != NULL) {  
  748.                 paintingColor = bgColor;  
  749.             } else {  
  750.                 paintingColor = SkColorSetARGB(0000);  
  751.             }  
  752.   
  753.             bm->eraseColor(paintingColor);  
  754.             fBackup.eraseColor(paintingColor);  
  755.         } else {  
  756.             // Dispose previous frame before move to next frame.  
  757.             const SavedImage* prev = &fGIF->SavedImages[i-1];  
  758.             disposeFrameIfNeeded(bm, prev, cur, &fBackup, paintingColor);  
  759.         }  
  760.   
  761.         // Draw frame  
  762.         // We can skip this process if this index is not last and disposal  
  763.         // method == 2 or method == 3  
  764.         if (i == lastIndex || !checkIfWillBeCleared(cur)) {  
  765.             drawFrame(bm, cur, gif->SColorMap);  
  766.         }  
  767.     }  
  768.   
  769.     // save index  
  770.     fLastDrawIndex = lastIndex;  
  771.     return true;  
  772. }  
  773.   
  774. ///////////////////////////////////////////////////////////////////////////////  
  775.   
  776. #include "SkTRegistry.h"  
  777.   
  778. SkMovie* Factory(SkStream* stream) {  
  779.     char buf[GIF_STAMP_LEN];  
  780.     if (stream->read(buf, GIF_STAMP_LEN) == GIF_STAMP_LEN) {  
  781.         if (memcmp(GIF_STAMP,   buf, GIF_STAMP_LEN) == 0 ||  
  782.                 memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||  
  783.                 memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0) {  
  784.             // must rewind here, since our construct wants to re-read the data  
  785.             stream->rewind();  
  786.             return SkNEW_ARGS(SkGIFMovie, (stream));  
  787.         }  
  788.     }  
  789.     return NULL;  
  790. }  
  791.   
  792. static SkTRegistry<SkMovie*, SkStream*> gReg(Factory);  

       完成以上Native层代码的修改,可别忘了修改AndroidSourceCode/external/skia/include/images/SkMovie.h哦,代码修改如下:
[cpp] view plaincopy
  1.      bool setTime(SkMSec);  
  2.     
  3. +    virtual int getGifFrameDuration(int frameIndex);  
  4. +    virtual int getGifTotalFrameCount();  
  5. +    SkBitmap* createGifFrameBitmap();  
  6. +    virtual bool setCurrFrame(int frameIndex);  
  7.      const SkBitmap& bitmap();  

       接下来就是调用具体的解码器来进行解码了,这部分内容因为系统已经做好了,因此到这里,gif的支持添加基本完成。

修改总览

       我们来看看总的修改吧,如图5:

                                                                                          图5

代码时序图

       图6是修改完成后,gif显示代码执行时序图:

                                                                  图6

总结

       因为自己从来没有接触过这些东西,起初看得真的是头大啊!当然,这么复杂的东西并不是我一个人搞定的,在多位朋友的帮助下,一点点的看,一点点的啃,当时记忆犹新的一句话就是 " 看这该死的代码看得都想吐了!!" " 吐完了回来继续看!!"针对这些不懂的东西,每个人一开始都是有畏惧感的,通过这件事情,让我知道,不管什么事情,一步一步来,稳扎稳打,总会守得云开见月明的。加油!!

       (PS:修改记录在这里,希望大家能共同讨论与学习。在此注明,修改中依然有很多“坑”,如果有像我这种小白的,请多多跟踪源码!!)